<?php
// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// 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);

use EasyInvoice\Providers\ClientServiceProvider;
use EasyInvoice\Providers\InvoiceServiceProvider;


// Get invoice ID if present in URL
$invoice_id = isset($_GET['invoice_id']) ? intval($_GET['invoice_id']) : 0;
$invoice = null;

// Check if this is a new invoice (no ID)
$is_new_invoice = ($invoice_id === 0);

// Default values for new invoice
$invoice_number_service = easy_invoice_get_invoice_number_service();
$invoice_data = array(
    'number' => $invoice_number_service->getNextNumber(),
    'date' => date('Y-m-d'),
    'due_date' => date('Y-m-d', strtotime('+30 days')),
    'client_id' => '',
    'client_name' => '',
    'client_email' => '',
    'client_phone' => '',
    'client_address' => '',
    'items' => array(),
    'notes' => '',
    'internal_notes' => '',
    'discount' => 0,
    'discount_type' => 'percentage',
    'calculation_method' => 'before_tax',
    'tax_rate' => 10,
    'prices_include_tax' => 'no',
    'payment_method' => 'bank_transfer',
    'payment_status' => 'unpaid',
    'currency' => 'USD',
    'currency_symbol' => '$',
    'title' => '',
    'description' => '',
    'terms' => '',
    'is_recurring' => 'no',
    'recurring_frequency' => '',
);

// Load clients for the dropdown
$client_repository = ClientServiceProvider::getClientRepository();
$clients = $client_repository->all();

// If editing an existing invoice, load its data
if ($invoice_id > 0) {
    // Get the invoice from repository
    $invoice_repository = InvoiceServiceProvider::getInvoiceRepository();
    $invoice = $invoice_repository->find($invoice_id);
} else {
    // Create a temporary WP_Post object for new invoice
    $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' => $invoice_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_POST_TYPE,
        'post_mime_type' => '',
        'comment_count' => 0,
        'filter' => 'raw',
    ));
    
    $invoice = new \EasyInvoice\Models\Invoice($empty_post);
    
    // Set default values on the invoice object
    foreach ($invoice_data as $key => $value) {
        $setter = 'set' . easy_invoice_str_replace('_', '', ucwords($key, '_'));
        if (method_exists($invoice, $setter)) {
            // Handle client_id specially to avoid type errors
            if ($key === 'client_id' && empty($value)) {
                $invoice->setClientId(0);
            } else {
                $invoice->$setter($value);
            }
        }
    }
    
    // Initialize empty items array
    $invoice->setItems([]);
}

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

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

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

// Prepare client data for JavaScript
$client_data_json = json_encode($client_data ?? null);

// Start output buffering to capture content

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

<div id="easy-invoice-content" class="h-screen flex flex-col bg-gray-50">
    <!-- Header -->
    <header class="ei-invoice-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-invoice-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 invoices', '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( 'Invoice', '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 w-full min-w-0 flex-wrap items-center justify-end gap-2 lg:w-auto lg:max-w-3xl lg:shrink-0">
                    <?php
                    if ( $invoice && $invoice_id > 0 ) {
                        do_action( 'easy_invoice_builder_before_invoice_actions', $invoice );
                    }
                    ?>
                    <button type="button" id="save-invoice-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['invoice_id'] ) ? esc_html__( 'Update invoice', 'easy-invoice' ) : esc_html__( 'Save invoice', 'easy-invoice' ); ?></span>
                    </button>
                    <button type="button" id="send-invoice-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_invoice_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 invoice', 'easy-invoice' ); ?></span>
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <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-invoice-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/invoices/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/invoices/live-preview.php'; ?>
                </div>
            </div>

            <!-- Add Client Modal -->
            <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-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-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);
                    include_once EASY_INVOICE_PLUGIN_DIR . 'templates/client-form.php'; 
                    ?>
                </div>
            </div>

            <input type="hidden" name="invoice_template" id="invoice_template" value="<?php echo esc_attr($invoice ? $invoice->getTemplate() : 'standard'); ?>" />
        </div>
    </div>
</div>

<script type="text/javascript">
jQuery(document).ready(function($) {
    var base = {
        ajaxUrl: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
        nonce: '<?php echo esc_js( wp_create_nonce( 'easy_invoice_nonce' ) ); ?>',
        clientData: <?php echo $client_data_json; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>,
        isPro: <?php echo easy_invoice_has_pro() ? 'true' : 'false'; ?>
    };
    window.easyInvoice = $.extend(true, {}, typeof window.easyInvoice === 'object' ? window.easyInvoice : {}, base);

    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 animate-spin 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-invoice-saved', function (e, response) {
        if (!pendingSend || !response || !response.success) {
            return;
        }
        pendingSend = false;
        if ($('#invoice-id').val() !== '0') {
            sendInvoiceEmail();
        }
    });
    $(document).on('easy-invoice-save-failed', function () {
        pendingSend = false;
    });

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

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

        var runAjax = function () {
            var $btn = $('#send-invoice-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_invoice_email',
                    invoice_id: invoiceId,
                    nonce: nonce
                },
                success: function (response) {
                    if (response.success) {
                        if (typeof EasyInvoiceToast !== 'undefined') {
                            EasyInvoiceToast.success(t('email_sent_invoice', 'Invoice email sent successfully.'));
                        }
                    } else {
                        var msg = (response.data && response.data.message) ? response.data.message : 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('invoice', runAjax);
        } else if (window.confirm(t('send_invoice_confirm_browser', 'Send this invoice by email?'))) {
            runAjax();
        }
    }
});
</script>


