<?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}
use EasyInvoice\Providers\ClientServiceProvider;
use EasyInvoice\Providers\QuoteServiceProvider;

// Enqueue CSS and JS files for the builder page
wp_enqueue_style('easy-invoice-form', plugin_dir_url(__FILE__) . '../../assets/css/invoice-form.css', array(), EASY_INVOICE_VERSION);
wp_enqueue_script('easy-invoice-form', plugin_dir_url(__FILE__) . '../../assets/js/invoice-form.js', array('jquery'), EASY_INVOICE_VERSION, true);
wp_enqueue_script('easy-client-manager', plugin_dir_url(__FILE__) . '../../assets/js/client-manager.js', array('jquery'), EASY_INVOICE_VERSION, true);

// Create nonce for AJAX calls
$ajax_nonce = wp_create_nonce('easy_invoice_nonce');

// Localize client manager script
wp_localize_script('easy-client-manager', 'easyInvoice', array(
    'ajaxUrl' => admin_url('admin-ajax.php'),
    'nonce' => $ajax_nonce
));

// Get quote ID if present in URL
$quote_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($quote_id) {
    $post = get_post($quote_id);
    if (!$post || $post->post_type !== \EasyInvoice\Constants\PostTypes::EASY_INVOICE_QUOTE_POST_TYPE) {
        wp_die(__('Invalid post type. This builder can only be used for quotes.', 'easy-invoice'), __('Invalid Post Type', 'easy-invoice'), array('back_link' => true));
    }
}
$quote = null;

// Check if this is a new quote (no ID)
$is_new_quote = ($quote_id === 0);

// Default values for new quote
$quote_number_service = function_exists('easy_invoice_get_quote_number_service') ? easy_invoice_get_quote_number_service() : null;

// Get global quote settings
$settings_controller = new \EasyInvoice\Controllers\SettingsController();
$quote_prefix = $settings_controller::getQuotePrefix();
$quote_terms = $settings_controller::getQuoteTermsConditions();
$quote_footer = $settings_controller::getQuoteFooterText();
$quote_accept_button = get_option('easy_invoice_quote_accept_button', 'yes');
$quote_accept_action = get_option('easy_invoice_quote_accept_action', 'email');
$quote_accept_text = get_option('easy_invoice_quote_accept_text', __('Accept Quote', 'easy-invoice'));
$quote_accepted_message = get_option('easy_invoice_quote_accepted_message', __('Thank you for accepting our quote!', 'easy-invoice'));
$quote_declined_message = get_option('easy_invoice_quote_declined_message', __('Thank you for your consideration.', 'easy-invoice'));

$quote_data = array(
    'number' => $quote_number_service ? $quote_number_service->getNextNumber() : 'QT-1',
    'date' => date('Y-m-d'),
    'expiry_date' => date('Y-m-d', strtotime('+30 days')),
    'client_id' => 0,
    'client_name' => '',
    'client_email' => '',
    'client_phone' => '',
    'client_address' => '',
    'items' => array(),
    'notes' => '',
    'internal_notes' => '',
    'discount' => 0,
    'discount_type' => 'percentage',
    'calculation_method' => 'before_tax',
    'tax_rate' => easy_invoice_get_tax_rate(),
    'prices_include_tax' => 'no',
    'status' => 'draft',
    'currency' => 'USD',
    'currency_symbol' => '$',
    'title' => '',
    'description' => '',
    'terms' => $quote_terms, // Use global terms setting
    'footer_text' => $quote_footer, // Use global footer setting
    'accept_button' => $quote_accept_button, // Use global accept button setting
    'accept_action' => $quote_accept_action, // Use global accept action setting
    'accept_text' => $quote_accept_text, // Use global accept text setting
    'accepted_message' => $quote_accepted_message, // Use global accepted message setting
    'declined_message' => $quote_declined_message, // Use global declined message setting
);

// Get clients from repository
$client_repository = ClientServiceProvider::getClientRepository();
$clients = $client_repository->all();

// Load client data directly in PHP if quote has a client
$client_data = null;
if ($quote && $quote->getClientId()) {
    $client = $client_repository->find($quote->getClientId());
    if ($client) {
        $client_data = array(
            'id' => $client->getId(),
            'name' => $client->getBusinessClientName() ?: ($client->getFirstName() . ' ' . $client->getLastName()),
            'email' => $client->getEmail() ?: '',
            'phone' => $client->getExtraInfo() ?: '',
            'company' => $client->getBusinessClientName() ?: '',
            'address' => $client->getAddress() ?: '',
            'website' => $client->getWebsite() ?: '',
        );
    }
}

// If editing an existing quote, load its data
if ($quote_id > 0) {
    // Get the quote from repository
    $quote_repository = QuoteServiceProvider::getQuoteRepository();
    $quote = $quote_repository->find($quote_id);

    if ($quote && $quote->getId()) {
        // Quote loaded successfully
    } else {
        // Failed to load quote
    }
} else {
    // Create a temporary WP_Post object for new quote
    $empty_post = new WP_Post((object) array(
        'ID' => 0,
        'post_author' => get_current_user_id(),
        'post_date' => current_time('mysql'),
        'post_date_gmt' => current_time('mysql', 1),
        'post_title' => $quote_data['number'],
        'post_status' => 'auto-draft',
        'comment_status' => 'closed',
        'ping_status' => 'closed',
        'post_name' => '',
        'post_modified' => current_time('mysql'),
        'post_modified_gmt' => current_time('mysql', 1),
        'post_parent' => 0,
        'guid' => '',
        'menu_order' => 0,
        'post_type' => \EasyInvoice\Constants\PostTypes::EASY_INVOICE_QUOTE_POST_TYPE,
        'post_mime_type' => '',
        'comment_count' => 0,
        'filter' => 'raw',
    ));

    $quote = new \EasyInvoice\Models\Quote($empty_post);

    // Set default values on the quote object
    foreach ($quote_data as $key => $value) {
        $setter = 'set' . easy_invoice_str_replace('_', '', ucwords($key, '_'));
        if (method_exists($quote, $setter)) {
            // Handle type-specific setters
            switch ($setter) {
                case 'setClientId':
                    $quote->setClientId((int) $value);
                    break;
                case 'setItems':
                    $quote->setItems((array) $value);
                    break;
                case 'setSubtotal':
                case 'setTaxAmount':
                case 'setDiscountAmount':
                case 'setTotal':
                case 'setDiscountValue':
                case 'setTaxRate':
                    $quote->$setter((float) $value);
                    break;
                case 'setPricesIncludeTax':
                    $quote->$setter((bool) $value);
                    break;
                default:
                    $quote->$setter((string) $value);
                    break;
            }
        }
    }

    // Initialize empty items array
    $quote->setItems([]);
}

// Only load custom meta that's not handled by Quote object
if ($quote) {
    // These are still accessed from meta as they don't have model methods yet
    $quote_data['terms'] = $quote_id > 0 ? get_post_meta($quote_id, '_easy_invoice_terms', true) : $quote_data['terms'];
    $quote_data['internal_notes'] = $quote_id > 0 ? get_post_meta($quote_id, '_easy_invoice_internal_notes', true) : $quote_data['internal_notes'];
    $quote_data['currency'] = $quote_id > 0 ? get_post_meta($quote_id, '_easy_invoice_currency_code', true) : $quote_data['currency'];
    $quote_data['currency_symbol'] = $quote_id > 0 ? get_post_meta($quote_id, '_easy_invoice_currency_position', true) : $quote_data['currency_symbol'];
    $quote_data['calculation_method'] = $quote_id > 0 ? get_post_meta($quote_id, '_easy_invoice_calculation_method', true) : $quote_data['calculation_method'];
}

// Prepare quote items JSON for JavaScript
$quote_items_json = json_encode($quote ? $quote->getItems() : []);

// Create nonce for AJAX calls
$admin_nonce = wp_create_nonce('easy_invoice_admin_nonce');

// Initialize quote form manager for field configuration
$quote_form_manager = new \EasyInvoice\Forms\Quote\QuoteFormManager();
$quote_field_config = $quote_form_manager->getFieldConfigForJavaScript();

// Remove the following code that preloads all templates into JS
// $templates = $quote_form_manager->getTemplates();
// $template_htmls = [];
// $formatter = new \EasyInvoice\Helpers\QuoteFormatter($quote);
// foreach ($templates as $template_id => $template_config) {
//     $template_file = EASY_INVOICE_PLUGIN_DIR . 'templates/quote-templates/' . $template_id . '.php';
//     if (file_exists($template_file)) {
//         ob_start();
//         include $template_file;
//         $template_htmls[$template_id] = ob_get_clean();
//     } else {
//         $template_htmls[$template_id] = '<div class="template-not-found"><h3>Template Not Found</h3><p>The template "' . esc_html($template_id) . '" does not exist.</p></div>';
//     }
// }

if ( $quote_id && $quote ) {
	$ei_header_display_title = $quote->title ?: $quote->number ?: __( 'Untitled quote', 'easy-invoice' );
} else {
	$ei_header_display_title = __( 'Create new quote', 'easy-invoice' );
}

?>

<script>
window.isQuoteForm = true;
</script>

<script>
jQuery(function ($) {
    window.easyInvoice = $.extend(true, {}, typeof window.easyInvoice === 'object' ? window.easyInvoice : {}, {
        fieldConfig: <?php echo wp_json_encode( $quote_field_config ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
        clientData: <?php echo wp_json_encode( $client_data ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
        ajaxUrl: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
        nonce: '<?php echo esc_js( wp_create_nonce( 'easy_invoice_nonce' ) ); ?>',
        isPro: <?php echo easy_invoice_has_pro() ? 'true' : 'false'; ?>
    });

    function t(key, fb) {
        return (window.easyInvoice && easyInvoice.i18n && easyInvoice.i18n[key]) ? easyInvoice.i18n[key] : fb;
    }
    var spin = '<svg class="ei-btn-spinner h-4 w-4 inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" aria-hidden="true"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>';
    var pendingSend = false;

    $(document).on('easy-quote-saved', function (e, response) {
        if (!pendingSend || !response || !response.success) {
            return;
        }
        pendingSend = false;
        if ($('#quote-id').val() !== '0') {
            sendQuoteEmail();
        }
    });
    $(document).on('easy-quote-save-failed', function () {
        pendingSend = false;
    });

    $('#send-quote-btn').on('click', function (e) {
        e.preventDefault();
        if ($('#quote-id').val() === '0') {
            pendingSend = true;
            $('#save-quote-btn').trigger('click');
            return;
        }
        sendQuoteEmail();
    });

    function sendQuoteEmail() {
        var quoteId = $('#quote-id').val();
        if (quoteId === '0') {
            if (typeof EasyInvoiceToast !== 'undefined') {
                EasyInvoiceToast.warning(t('save_first_quote', 'Please save the quote before sending.'));
            }
            return;
        }
        var nonce = $('#send-quote-btn').data('send-nonce') || '<?php echo esc_js( wp_create_nonce( 'easy_invoice_send_quote_email' ) ); ?>';

        var runAjax = function () {
            var $btn = $('#send-quote-btn');
            var original = $btn.html();
            $btn.prop('disabled', true).attr('aria-busy', 'true').html('<span class="inline-flex items-center gap-2">' + spin + '<span>' + t('sending', 'Sending…') + '</span></span>');
            $.ajax({
                url: window.easyInvoice.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'easy_invoice_send_quote_email',
                    quote_id: quoteId,
                    nonce: nonce
                },
                success: function (response) {
                    if (response.success) {
                        if (typeof EasyInvoiceToast !== 'undefined') {
                            EasyInvoiceToast.success(t('email_sent_quote', 'Quote email sent successfully.'));
                        }
                    } else {
                        var msg = (response.data && response.data.message) ? response.data.message : (response.data || t('email_error', 'Error sending email.'));
                        if (typeof EasyInvoiceToast !== 'undefined') {
                            EasyInvoiceToast.error(msg);
                        }
                    }
                },
                error: function () {
                    if (typeof EasyInvoiceToast !== 'undefined') {
                        EasyInvoiceToast.error(t('network_error', 'Error connecting to server.'));
                    }
                },
                complete: function () {
                    $btn.prop('disabled', false).removeAttr('aria-busy').html(original);
                }
            });
        };

        if (typeof EasyInvoiceConfirmation !== 'undefined') {
            EasyInvoiceConfirmation.confirmSendDocument('quote', runAjax);
        } else if (window.confirm(t('send_quote_confirm_browser', 'Send this quote by email?'))) {
            runAjax();
        }
    }
});
</script>

<form id="quote-form" method="post">
    <input type="hidden" id="quote-id" name="quote_id" value="<?php echo $quote_id; ?>">
    <input type="hidden" id="quote_nonce" name="quote_nonce" value="<?php echo wp_create_nonce('easy_invoice_nonce'); ?>">

    <div id="easy-invoice-content" class="h-screen flex flex-col bg-gray-50">
        <header class="ei-quote-builder-header ei-app-header-sync bg-white border-b border-gray-200 shadow-sm w-full z-10 box-border">
            <div class="max-w-full mx-auto h-full px-4 sm:px-5">
                <div class="ei-app-header-inner flex flex-col gap-3 py-3 sm:gap-4 lg:flex-row lg:items-center lg:justify-between lg:gap-6 lg:py-0 lg:h-full">
                    <div class="ei-app-header-leading flex min-w-0 flex-1 flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">
                        <a href="<?php echo esc_url( admin_url( 'admin.php?page=easy-quote-all' ) ); ?>"
                           class="inline-flex shrink-0 items-center gap-2 self-start rounded-md text-sm font-medium text-gray-600 hover:text-gray-900 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">
                            <svg class="h-4 w-4 shrink-0" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                            </svg>
                            <span><?php esc_html_e( 'Back to quotes', 'easy-invoice' ); ?></span>
                        </a>
                        <div class="min-w-0 flex-1 border-l-0 sm:border-l sm:border-gray-200 sm:pl-4">
                            <p class="text-xs font-medium uppercase tracking-wide text-gray-500"><?php esc_html_e( 'Quote', 'easy-invoice' ); ?></p>
                            <h1 id="ei-builder-header-title" class="mt-0.5 truncate text-lg font-semibold leading-tight text-gray-900 sm:text-xl" data-ei-default="<?php echo esc_attr( $ei_header_display_title ); ?>">
                                <?php echo esc_html( $ei_header_display_title ); ?>
                            </h1>
                            <p class="sr-only"><?php esc_html_e( 'The title above matches the document title field in the editor.', 'easy-invoice' ); ?></p>
                        </div>
                    </div>
                    <div class="ei-builder-header-actions flex flex-wrap items-center gap-2 lg:shrink-0">
                        <button type="button" id="save-quote-btn" class="inline-flex items-center gap-2 px-3 sm:px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" aria-busy="false">
                            <svg class="h-4 w-4 text-gray-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"></path>
                            </svg>
                            <span><?php echo isset( $_GET['id'] ) ? esc_html__( 'Update quote', 'easy-invoice' ) : esc_html__( 'Save quote', 'easy-invoice' ); ?></span>
                        </button>
                        <button type="button" id="send-quote-btn" class="inline-flex items-center gap-2 px-3 sm:px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500" data-send-nonce="<?php echo esc_attr( wp_create_nonce( 'easy_invoice_send_quote_email' ) ); ?>">
                            <svg class="h-4 w-4 shrink-0" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true">
                                <path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75"></path>
                            </svg>
                            <span><?php esc_html_e( 'Send quote', 'easy-invoice' ); ?></span>
                        </button>
                    </div>
                </div>
            </div>
        </header>

        <div class="flex-grow overflow-y-auto min-h-0">
            <div class="max-w-full mx-auto px-4 sm:px-5 py-4 sm:py-5">
                <div class="ei-builder-tabs lg:hidden flex rounded-lg bg-gray-100 p-1 gap-1 mb-4" role="tablist" aria-label="<?php echo esc_attr__( 'Editor panels', 'easy-invoice' ); ?>">
                    <button type="button" role="tab" class="ei-builder-tab flex-1 rounded-md py-2 text-sm font-medium transition bg-white shadow-sm text-indigo-700" data-tab="editor" aria-selected="true"><?php esc_html_e( 'Editor', 'easy-invoice' ); ?></button>
                    <button type="button" role="tab" class="ei-builder-tab flex-1 rounded-md py-2 text-sm font-medium transition text-gray-600 hover:text-gray-800" data-tab="preview" aria-selected="false"><?php esc_html_e( 'Preview', 'easy-invoice' ); ?></button>
                </div>
                <div id="ei-builder-shell-hint" class="ei-builder-shell-hint mb-4 hidden rounded-md border border-indigo-100 bg-indigo-50/90 p-3 text-sm text-gray-700 shadow-sm lg:hidden" role="status" hidden>
                    <div class="flex items-start gap-3">
                        <span class="mt-0.5 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-indigo-100 text-indigo-700" aria-hidden="true">
                            <svg class="h-3.5 w-3.5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                        </span>
                        <p class="min-w-0 flex-1 leading-snug"><?php esc_html_e( 'On smaller screens, use the tabs to switch between the editor and the live preview.', 'easy-invoice' ); ?></p>
                        <button type="button" id="ei-builder-shell-hint-dismiss" class="shrink-0 rounded-md px-2 py-1 text-xs font-medium text-indigo-700 hover:bg-indigo-100 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            <?php esc_html_e( 'Got it', 'easy-invoice' ); ?>
                        </button>
                    </div>
                </div>
                <div id="ei-quote-builder-grid" class="grid grid-cols-1 lg:grid-cols-2 gap-6 lg:gap-8">
                    <div id="ei-builder-editor" class="min-w-0 ei-builder-panel-editor">
                        <?php include_once EASY_INVOICE_PLUGIN_DIR . 'templates/quotes/form.php'; ?>
                    </div>
                    <div id="ei-builder-preview" class="min-w-0 ei-builder-panel-preview hidden lg:block">
                        <?php include_once EASY_INVOICE_PLUGIN_DIR . 'templates/quotes/live-preview.php'; ?>
                    </div>
                </div>

                <div id="add_client_modal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-75 overflow-y-auto h-full w-full z-50" role="dialog" aria-modal="true" aria-labelledby="ei-quote-add-client-title">
                    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-2/3 lg:w-1/2 shadow-lg rounded-md bg-white">
                        <div class="flex justify-between items-center mb-4">
                            <h3 id="ei-quote-add-client-title" class="text-lg font-medium text-gray-900"><?php esc_html_e( 'Add new client', 'easy-invoice' ); ?></h3>
                            <button type="button" class="close-modal rounded-md p-1 text-gray-400 hover:text-gray-600 focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                <span class="sr-only"><?php esc_html_e( 'Close', 'easy-invoice' ); ?></span>
                                <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                </svg>
                            </button>
                        </div>

                        <?php
                        // Unset the $client variable from the foreach loop to ensure clean add form
                        unset($client);
                        // Also unset any client variable that might have been set in form.php
                        if (isset($client)) {
                            unset($client);
                        }
                        include_once EASY_INVOICE_PLUGIN_DIR . 'templates/client-form.php';
                        ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>



