<?php
/**
 * Quote Form Manager Class
 *
 * @package     EasyInvoice
 * @author      Your Name
 * @copyright   Copyright (c) 2023, Your Company
 * @license     http://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       1.0.0
 */

namespace EasyInvoice\Forms\Quote;

use EasyInvoice\Forms\BaseFormManager;

/**
 * Quote Form Manager
 *
 * Handles quote-specific form management, rendering, and processing.
 *
 * @since 1.0.0
 */
class QuoteFormManager extends BaseFormManager {
    
    /**
     * Constructor
     *
     * @since 1.0.0
     */
    public function __construct() {
        // Initialize quote-specific field registration first
        $this->field_registration = new QuoteFieldRegistration();
        
        // Call parent constructor (which will call initializeDefaults)
        parent::__construct();
    }
    
    /**
     * Initialize default tabs, fields, and templates
     *
     * @since 1.0.0
     * @return void
     */
    protected function initializeDefaults(): void {
        // Register default tabs
        $this->field_registration->registerDefaultTabs();
        
        // Register default fields
        $this->field_registration->registerDefaultFields();
        
        // Register default templates
        $this->field_registration->registerDefaultTemplates();
        
        // Register default item fields
        $this->field_registration->registerDefaultItemFields();
    }
    
    /**
     * Get form templates
     *
     * @since 1.0.0
     * @return array
     */
    public function getTemplates(): array {
        return $this->field_registration->getTemplates();
    }
    
    /**
     * Get item fields
     *
     * @since 1.0.0
     * @return array
     */
    public function getItemFields(): array {
        return $this->field_registration->getItemFields();
    }
    
    /**
     * Get fields for a specific tab
     *
     * @since 1.0.0
     * @param string $tab_id
     * @return array
     */
    public function getFieldsForTab(string $tab_id): array {
        return $this->field_registration->getFieldsForTab($tab_id);
    }
    
    /**
     * Render form field
     *
     * @since 1.0.0
     * @param array $field_config
     * @param mixed $value
     * @return string
     */
    public function renderField(array $field_config, $value = null): string {
        return $this->field_renderer->renderField($field_config, $value);
    }
    
    /**
     * Render form tab
     *
     * @since 1.0.0
     * @param string $tab_id
     * @param array $tab_config
     * @param array $fields
     * @param array $data
     * @return string
     */
    public function renderTab(string $tab_id, array $tab_config, array $fields, array $data = []): string {
        return $this->tab_renderer->render($tab_id, $tab_config, $fields, $data);
    }
    
    /**
     * Process form data
     *
     * @since 1.0.0
     * @param array $data
     * @return array
     */
    public function processFormData(array $data): array {
        return $this->form_processor->processFormData($data, $this->getAllFields());
    }
    
    /**
     * Process items data
     *
     * @since 1.0.0
     * @param array $items_data
     * @return array
     */
    public function processItemsData(array $items_data): array {
        return $this->form_processor->processItemsData($items_data, $this->getItemFields());
    }
    
    /**
     * Validate form data
     *
     * @since 1.0.0
     * @param array $data
     * @return array
     */
    public function validateFormData(array $data): array {
        return $this->form_validator->validate($data, $this->getAllFields());
    }
    
    /**
     * Get form errors
     *
     * @since 1.0.0
     * @return array
     */
    public function getErrors(): array {
        return $this->form_validator->getErrors();
    }
    
    /**
     * Clear form errors
     *
     * @since 1.0.0
     * @return void
     */
    public function clearErrors(): void {
        $this->form_validator->clearErrors();
    }
    
    /**
     * Get the form type
     *
     * @since 1.0.0
     * @return string
     */
    protected function getFormType(): string {
        return 'quote';
    }
    
    /**
     * Get the form action
     *
     * @since 1.0.0
     * @return string
     */
    protected function getFormAction(): string {
        return admin_url('admin-ajax.php');
    }
    
    /**
     * Get the form method
     *
     * @since 1.0.0
     * @return string
     */
    protected function getFormMethod(): string {
        return 'POST';
    }
    
    /**
     * Get the form enctype
     *
     * @since 1.0.0
     * @return string
     */
    protected function getFormEnctype(): string {
        return 'multipart/form-data';
    }
    
    /**
     * Get the form class
     *
     * @since 1.0.0
     * @return string
     */
    protected function getFormClass(): string {
        return 'easy-invoice-form quote-form';
    }
    
    /**
     * Get the form ID
     *
     * @since 1.0.0
     * @return string
     */
    protected function getFormId(): string {
        return 'easy-invoice-quote-form';
    }
    
    /**
     * Get the form nonce action
     *
     * @since 1.0.0
     * @return string
     */
    protected function getFormNonceAction(): string {
        return 'easy_invoice_quote_form_nonce';
    }
    
    /**
     * Get the form nonce field name
     *
     * @since 1.0.0
     * @return string
     */
    protected function getFormNonceFieldName(): string {
        return 'easy_invoice_quote_nonce';
    }
    
    /**
     * Get the form submit button text
     *
     * @since 1.0.0
     * @return string
     */
    protected function getSubmitButtonText(): string {
        return __('Save Quote', 'easy-invoice');
    }
    
    /**
     * Get the form submit button class
     *
     * @since 1.0.0
     * @return string
     */
    protected function getSubmitButtonClass(): string {
        return 'button button-primary easy-invoice-submit';
    }
    
    /**
     * Get the form submit button ID
     *
     * @since 1.0.0
     * @return string
     */
    protected function getSubmitButtonId(): string {
        return 'easy-invoice-quote-submit';
    }
    
    /**
     * Get the form submit button name
     *
     * @since 1.0.0
     * @return string
     */
    protected function getSubmitButtonName(): string {
        return 'easy_invoice_quote_submit';
    }
    
    /**
     * Get the form submit button value
     *
     * @since 1.0.0
     * @return string
     */
    protected function getSubmitButtonValue(): string {
        return 'save_quote';
    }
    
    /**
     * Get the form action field name
     *
     * @since 1.0.0
     * @return string
     */
    protected function getActionFieldName(): string {
        return 'action';
    }
    
    /**
     * Get the form action field value
     *
     * @since 1.0.0
     * @return string
     */
    protected function getActionFieldValue(): string {
        return 'easy_invoice_save_quote';
    }
    
    /**
     * Get the form quote ID field name
     *
     * @since 1.0.0
     * @return string
     */
    protected function getQuoteIdFieldName(): string {
        return 'quote_id';
    }
    
    /**
     * Get the form quote ID field value
     *
     * @since 1.0.0
     * @param int $quote_id
     * @return string
     */
    protected function getQuoteIdFieldValue(int $quote_id = 0): string {
        return (string) $quote_id;
    }
    
    /**
     * Get the form quote ID field type
     *
     * @since 1.0.0
     * @return string
     */
    protected function getQuoteIdFieldType(): string {
        return 'hidden';
    }
    
    /**
     * Get the form quote ID field class
     *
     * @since 1.0.0
     * @return string
     */
    protected function getQuoteIdFieldClass(): string {
        return 'easy-invoice-quote-id';
    }
    
    /**
     * Get the form quote ID field ID
     *
     * @since 1.0.0
     * @return string
     */
    protected function getQuoteIdFieldId(): string {
        return 'easy-invoice-quote-id';
    }
    
    /**
     * Get field configuration for JavaScript
     *
     * @since 1.0.0
     * @return array
     */
    public function getFieldConfigForJavaScript(): array {
        $config = [
            'tabs' => $this->getTabs(),
            'fields' => [],
            'templates' => $this->getTemplates(),
            'itemFields' => $this->getItemFields()
        ];
        
        // Get fields for each tab
        $tabs = $this->getTabs();
        foreach ($tabs as $tab_id => $tab_config) {
            $config['fields'][$tab_id] = $this->getFields($tab_id);
        }
        
        return $config;
    }
    
    /**
     * Generate HTML for a blank (template) quote item
     *
     * @since 1.0.0
     * @return string
     */
    public function generateItemTemplateHtml(): string {
        return $this->item_field_renderer->generateItemTemplateHtml($this->field_registration);
    }
    
    /**
     * Render all item fields for an existing item
     *
     * @since 1.0.0
     * @param object $item The item object
     * @param int $index The item index
     * @return string
     */
    public function generateExistingItemHtml($item, int $index): string {
        $html = '';
        $fields = $this->getItemFields();
        
        // Wrap fields in a grid container
        $html .= '<div class="grid grid-cols-1 gap-y-6 gap-x-4 sm:grid-cols-4">';
        
        foreach ($fields as $field) {
            $field_name = $field['name'] ?? '';
            $value = '';
            
            // Map field names to the correct getter methods
            $getter_map = [
                'title' => 'getName',
                'name' => 'getName',
                'description' => 'getDescription',
                'quantity' => 'getQuantity',
                'price' => 'getPrice',
                'total' => 'getAmount',
                'amount' => 'getAmount',
                'taxable' => 'getTaxable',
                'adjust_percentage' => 'getAdjustPercentage'
            ];
            
            // Try to get the value from the item object using the mapped getter
            if (isset($getter_map[$field_name]) && method_exists($item, $getter_map[$field_name])) {
                $getter = $getter_map[$field_name];
                $value = $item->$getter();
            } elseif (is_array($item) && isset($item[$field_name])) {
                $value = $item[$field_name];
            } else {
                // Try dynamic getter for fields not in the map
                $getter = 'get' . easy_invoice_str_replace(' ', '', ucwords(easy_invoice_str_replace('_', ' ', $field_name)));
                try {
                    $value = $item->$getter();
                } catch (\BadMethodCallException $e) {
                    $value = '';
                }
            }
            
            $html .= $this->item_field_renderer->renderItemField($field, $index, $value);
        }
        
        $html .= '</div>';
        
        return $html;
    }
} 