<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>

<?php
$client_info = $this->invoice_model->check_by(array('client_id' => $project_info->client_id), 'tbl_client');
$currency = $this->invoice_model->client_currency_symbol($project_info->client_id);
$client_lang = $client_info->language;
unset($this->lang->is_loaded[5]);
$language_info = $this->lang->load('sales_lang', $client_lang, TRUE, FALSE, '', TRUE);

$client_id = null;
if (!empty($project_info->client_id)) {
    $client_id = $project_info->client_id;
} elseif (!empty($invoice_info->client_id)) {
    $client_id = $invoice_info->client_id;
}

$project_id_selected = null;
if (!empty($project_info->project_id)) {
    $project_id_selected = $project_info->project_id;
} elseif (!empty($invoice_info->project_id)) {
    $project_id_selected = $invoice_info->project_id;
}

if (!empty($invoice_info) && $invoice_info->recurring == 'Yes') {
    $recur_start_date = date('Y-m-d', safe_strtotime($invoice_info->recur_start_date));
    $recur_end_date = date('Y-m-d', safe_strtotime($invoice_info->recur_end_date));
} else {
    $recur_start_date = date('Y-m-d');
    $recur_end_date = date('Y-m-d');
}

$reference_no = '';
if (!empty($invoice_info)) {
    $reference_no = $invoice_info->reference_no;
} else {
    if (empty(config_item('invoice_number_format'))) {
        $reference_no .= config_item('invoice_prefix');
    }
    if (config_item('increment_invoice_number') == 'FALSE') {
        $this->load->helper('string');
        $reference_no .= random_string('nozero', 6);
    } else {
        $reference_no .= $this->invoice_model->generate_invoice_number();
    }
}

$permissionL = !empty($invoice_info->permission) ? $invoice_info->permission : null;
$invoices_id = !empty($invoice_info) ? $invoice_info->invoices_id : null;
$all_project = array();
if (!empty($client_id)) {
    $all_project = $this->db->where('client_id', $client_id)->get('tbl_project')->result();
}

if (!empty($tasks)) {
    $tasks = $tasks;
} else {
    $tasks = null;
}

if (!empty($expense)) {
    $expense = $expense;
} else {
    $expense = null;
}

$pdata['itemType'] = 'projectInvoice';
if (!empty($project_info)) {
    $pdata['add_items'] = $this->items_model->make_all_items($project_info->project_id, $items_name, $tasks, $expense, true);
    $pdata['warehouseId'] = null;
}

$preview_items = array();
if (!empty($pdata['add_items'])) {
    if (is_string($pdata['add_items'])) {
        $decoded_preview_items = json_decode($pdata['add_items']);
        if (json_last_error() === JSON_ERROR_NONE && is_array($decoded_preview_items)) {
            $preview_items = $decoded_preview_items;
        }
    } elseif (is_array($pdata['add_items'])) {
        $preview_items = $pdata['add_items'];
    }
}
$preview_show_quantity = !empty($invoice_info->show_quantity_as) ? $invoice_info->show_quantity_as : 'qty';
$preview_discount_percent = !empty($invoice_info->discount_percent) ? $invoice_info->discount_percent : 0;
$preview_discount_type = !empty($invoice_info->discount_type) ? $invoice_info->discount_type : 'percent';
$preview_adjustment = !empty($invoice_info->adjustment) ? $invoice_info->adjustment : 0;

$custom_fields_html = custom_form_Fields(9, $invoices_id);

$client_options = array('-' => lang('select') . ' ' . lang('client'));
if (!empty($all_client)) {
    foreach ($all_client as $v_client) {
        $client_options[$v_client->client_id] = ucfirst($v_client->name);
    }
}

$project_options = array('' => lang('none'));
if (!empty($all_project)) {
    foreach ($all_project as $v_project) {
        $project_options[$v_project->project_id] = $v_project->project_name;
    }
}

$agent_options = array('' => lang('select') . ' ' . lang('sales') . ' ' . lang('agent'));
$all_user = $this->db->where('role_id != ', 2)->get('tbl_users')->result();
if (!empty($all_user)) {
    foreach ($all_user as $v_user) {
        $profile_info = $this->db->where('user_id', $v_user->user_id)->get('tbl_account_details')->row();
        if (!empty($profile_info)) {
            $agent_options[$v_user->user_id] = $profile_info->fullname;
        }
    }
}

$selected_agent = !empty($invoice_info->user_id) ? $invoice_info->user_id : $this->session->userdata('user_id');
$invoice_date_value = !empty($invoice_info->invoice_date) ? $invoice_info->invoice_date : date('Y-m-d');
$due_date_value = !empty($invoice_info->due_date) ? $invoice_info->due_date : date('Y-m-d');
$recur_frequency = !empty($invoice_info->recur_frequency) ? $invoice_info->recur_frequency : 'none';
$recur_frequency_options = array(
    'none' => lang('none'),
    '7D' => lang('week'),
    '1M' => lang('month'),
    '3M' => lang('quarter'),
    '6M' => lang('six_months'),
    '1Y' => lang('1year'),
    '2Y' => lang('2year'),
    '3Y' => lang('3year'),
);
?>

<form action="<?= base_url() ?>admin/projects/save_invoice/<?php if (!empty($project_info->project_id)) {
    echo $project_info->project_id;
} ?>" method="post" enctype="multipart/form-data" id="project-invoice-preview-form" class="space-y-6">
    <div class="rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:border-[#213047] dark:bg-[#0f1726] dark:shadow-none">
        <div class="border-b border-slate-200 pb-6 dark:border-[#213047]">
            <div class="flex flex-col gap-5 xl:flex-row xl:items-start xl:justify-between">
                <div class="space-y-4">
                    <div class="inline-flex items-center gap-2 rounded-full border border-indigo-200 bg-indigo-50 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-indigo-700 dark:border-indigo-500/30 dark:bg-indigo-500/10 dark:text-indigo-200">
                        <i data-lucide="file-text"></i>
                        <?= lang('preview_invoice') ?>
                    </div>
                    <div>
                        <h1 class="text-[28px] font-semibold tracking-tight text-slate-950 dark:text-white"><?= $project_info->project_name ?></h1>
                        <p class="mt-2 max-w-3xl text-sm leading-6 text-slate-500 dark:text-slate-400">
                            Review the invoice draft, adjust billable items, and save the final client-ready invoice.
                        </p>
                    </div>
                </div>

                <div class="flex flex-wrap items-center gap-3">
                    <a href="<?= base_url() ?>admin/projects/project_details/<?= $project_info->project_id ?>" class="inline-flex items-center gap-2 rounded-2xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 transition hover:border-slate-400 hover:text-slate-900 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 dark:hover:border-slate-600 dark:hover:text-white">
                        <i class="fa fa-arrow-left"></i>
                        <?= lang('back') ?>
                    </a>
                    <button type="submit" name="save_as_draft" value="1" class="inline-flex items-center gap-2 rounded-2xl bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-500">
                        <i data-lucide="save"></i>
                        <?= lang('save') ?>
                    </button>
                    <button type="submit" name="create" value="1" class="inline-flex items-center gap-2 rounded-2xl bg-slate-950 px-5 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-slate-800 dark:bg-white dark:text-slate-950 dark:hover:bg-slate-100">
                        <i class="fa fa-paper-plane"></i>
                        <?= lang('invoice_project') ?>
                    </button>
                </div>
            </div>

            <div class="mt-6 grid gap-3 md:grid-cols-2 xl:grid-cols-4">
                <div class="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 dark:border-[#2c3b53] dark:bg-[#121d2d]">
                    <div class="text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400"><?= lang('client') ?></div>
                    <div class="mt-2 text-base font-semibold text-slate-900 dark:text-slate-100"><?= !empty($client_info->name) ? ucfirst($client_info->name) : '-' ?></div>
                </div>
                <div class="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 dark:border-[#2c3b53] dark:bg-[#121d2d]">
                    <div class="text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400"><?= lang('currency') ?></div>
                    <div class="mt-2 text-base font-semibold text-slate-900 dark:text-slate-100"><?= !empty($currency->symbol) ? $currency->symbol : default_currency() ?></div>
                </div>
                <div class="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 dark:border-[#2c3b53] dark:bg-[#121d2d]">
                    <div class="text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400"><?= lang('reference_no') ?></div>
                    <div class="mt-2 text-base font-semibold text-slate-900 dark:text-slate-100"><?= $reference_no ?></div>
                </div>
                <div class="rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 dark:border-[#2c3b53] dark:bg-[#121d2d]">
                    <div class="text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400"><?= lang('project') ?></div>
                    <div class="mt-2 text-base font-semibold text-slate-900 dark:text-slate-100">#<?= $project_info->project_id ?></div>
                </div>
            </div>
        </div>

        <div class="grid gap-6 px-0 py-6 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]">
            <div class="space-y-6">
                <section class="rounded-xl border border-slate-200 bg-white p-5 dark:border-[#213047] dark:bg-[#0b1220]">
                    <div class="mb-5 flex flex-wrap items-center justify-between gap-3">
                        <div>
                            <h2 class="text-lg font-semibold text-slate-950 dark:text-white"><?= lang('invoice') ?> <?= lang('details') ?></h2>
                            <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Configure reference, client assignment, dates, and recurring behavior.</p>
                        </div>
                        <button type="button" class="inline-flex items-center gap-2 rounded-xl border border-indigo-200 bg-indigo-50 px-3 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-indigo-700 transition hover:bg-indigo-100 dark:border-indigo-500/30 dark:bg-indigo-500/10 dark:text-indigo-200" id="start_recurring">
                            <i class="fa fa-refresh"></i>
                            <?= lang('recurring') ?>
                        </button>
                    </div>

                    <div class="grid gap-5 md:grid-cols-2">
                        <?= form_input_group('reference_no', lang('reference_no'), $reference_no, 'text', true, array('placeholder' => lang('reference_no'))); ?>

                        <?= form_select_group('client_id', lang('client'), $client_options, $client_id, true, array(
                            'class' => 'select_box',
                            'style' => 'width:100%',
                            'onchange' => 'get_project_by_id(this.value)',
                        )); ?>

                        <?= form_select_group('project_id', lang('project'), $project_options, $project_id_selected, false, array(
                            'id' => 'client_project',
                            'style' => 'width:100%',
                        )); ?>

                        <?= form_select_group('user_id', lang('sales') . ' ' . lang('agent'), $agent_options, $selected_agent, true, array(
                            'class' => 'select_box',
                            'style' => 'width:100%',
                        )); ?>

                        <?= form_datepicker('invoice_date', lang('invoice_date'), $invoice_date_value, false, array(
                            'data-format' => config_item('date_picker_format'),
                            'data-date-format' => config_item('date_picker_format'),
                        )); ?>

                        <?= form_datepicker('due_date', lang('due_date'), $due_date_value, false, array(
                            'data-format' => config_item('date_picker_format'),
                            'data-date-format' => config_item('date_picker_format'),
                        )); ?>
                    </div>

                    <div id="recurring" class="<?= !empty($invoice_info) && $invoice_info->recurring == 'Yes' ? '' : 'hidden hide' ?> mt-5 rounded-2xl border border-dashed border-indigo-200 bg-indigo-50/50 p-5 dark:border-indigo-500/20 dark:bg-indigo-500/10">
                        <div class="mb-4">
                            <h3 class="text-base font-semibold text-slate-900 dark:text-slate-100"><?= lang('recurring') ?> <?= lang('setup') ?></h3>
                            <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Set the cadence and active period for recurring invoice generation.</p>
                        </div>
                        <div class="grid gap-5 md:grid-cols-3">
                            <?= form_select_group('recuring_frequency', lang('recur_frequency'), $recur_frequency_options, $recur_frequency, false, array(
                                'id' => 'recuring_frequency',
                            )); ?>
                            <?= form_datepicker('recur_start_date', lang('start_date'), $recur_start_date, false, array(
                                'data-format' => config_item('date_picker_format'),
                                'data-date-format' => config_item('date_picker_format'),
                            )); ?>
                            <?= form_datepicker('recur_end_date', lang('end_date'), $recur_end_date, false, array(
                                'data-format' => config_item('date_picker_format'),
                                'data-date-format' => config_item('date_picker_format'),
                            )); ?>
                        </div>
                    </div>
                </section>

                <section class="rounded-xl border border-slate-200 bg-white p-5 dark:border-[#213047] dark:bg-[#0b1220]">
                    <div class="mb-5">
                        <h2 class="text-lg font-semibold text-slate-950 dark:text-white"><?= lang('notes') ?> & <?= lang('line_items') ?></h2>
                        <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Use the same editing flow as the main invoice screen before saving this project invoice.</p>
                    </div>

                    <div class="mb-6">
                        <?= form_editor('notes', lang('notes'), !empty($invoice_info) ? $invoice_info->notes : $this->config->item('default_terms'), false); ?>
                    </div>

                    <div class="rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-[#213047] dark:bg-[#111b2b]">
                        <?php
                        $this->load->view('admin/common/sales_items_editor', array(
                            'items' => $preview_items,
                            'show_quantity_as' => $preview_show_quantity,
                            'discount_percent' => $preview_discount_percent,
                            'discount_type' => $preview_discount_type,
                            'adjustment' => $preview_adjustment,
                            'currency_symbol' => !empty($currency->symbol) ? $currency->symbol : '',
                            'itemType' => 'projectInvoicePreview',
                        ));
                        ?>
                    </div>
                </section>
            </div>

            <div class="space-y-6">
                <section class="rounded-xl border border-slate-200 bg-white p-5 dark:border-[#213047] dark:bg-[#0b1220]">
                    <div class="mb-5">
                        <h2 class="text-lg font-semibold text-slate-950 dark:text-white"><?= ucfirst(lang('workflow')) ?> & <?= lang('visibility') ?></h2>
                        <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Control gateway availability, client visibility, and invoice-level permissions.</p>
                    </div>

                    <div class="space-y-4">
                        <?php
                        $all_payment = get_result('tbl_online_payment');
                        foreach ($all_payment as $payment) {
                            $allow_gateway = 'allow_' . slug_it(strtolower($payment->gateway_name));
                            $gateway_status = slug_it(strtolower($payment->gateway_name)) . '_status';
                            if (config_item($gateway_status) == 'active') { ?>
                                <label class="flex items-center justify-between gap-4 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 dark:border-[#2c3b53] dark:bg-[#121d2d]">
                                    <span>
                                        <span class="block text-sm font-semibold text-slate-900 dark:text-slate-100"><?= lang($allow_gateway) ?></span>
                                        <span class="mt-1 block text-xs text-slate-500 dark:text-slate-400"><?= $payment->gateway_name ?></span>
                                    </span>
                                    <span class="relative inline-flex items-center">
                                        <input type="checkbox" value="Yes" <?= !empty($invoice_info) && $invoice_info->$allow_gateway == 'Yes' ? 'checked' : '' ?> name="<?= $allow_gateway ?>" class="peer sr-only">
                                        <span class="h-6 w-11 rounded-full bg-slate-300 transition peer-checked:bg-emerald-500 dark:bg-slate-700"></span>
                                        <span class="absolute left-0.5 top-0.5 h-5 w-5 rounded-full bg-white shadow-sm transition peer-checked:translate-x-5"></span>
                                    </span>
                                </label>
                            <?php }
                        } ?>

                        <?php if (!empty($project_id)) : ?>
                            <label class="flex items-center justify-between gap-4 rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 dark:border-[#2c3b53] dark:bg-[#121d2d]">
                                <span>
                                    <span class="block text-sm font-semibold text-slate-900 dark:text-slate-100"><?= lang('visible_to_client') ?></span>
                                    <span class="mt-1 block text-xs text-slate-500 dark:text-slate-400">Allow this invoice to be visible in the client panel.</span>
                                </span>
                                <span class="relative inline-flex items-center">
                                    <input data-toggle="toggle" name="client_visible" value="Yes" <?= !empty($invoice_info->client_visible) && $invoice_info->client_visible == 'Yes' ? 'checked' : '' ?> data-on="<?= lang('yes') ?>" data-off="<?= lang('no') ?>" data-onstyle="success" data-offstyle="danger" type="checkbox" class="peer sr-only">
                                    <span class="h-6 w-11 rounded-full bg-slate-300 transition peer-checked:bg-indigo-600 dark:bg-slate-700"></span>
                                    <span class="absolute left-0.5 top-0.5 h-5 w-5 rounded-full bg-white shadow-sm transition peer-checked:translate-x-5"></span>
                                </span>
                            </label>
                        <?php endif ?>
                    </div>
                </section>

                <section class="rounded-xl border border-slate-200 bg-white p-5 dark:border-[#213047] dark:bg-[#0b1220]">
                    <div class="mb-5">
                        <h2 class="text-lg font-semibold text-slate-950 dark:text-white"><?= lang('warehouse') ?> & <?= lang('permissions') ?></h2>
                        <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Assign storage scope and decide who can access or manage this invoice.</p>
                    </div>

                    <div class="space-y-5">
                        <div class="rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-[#2c3b53] dark:bg-[#121d2d]">
                            <?php $this->load->view('admin/items/warehouselist', array('warehouse_required' => false)) ?>
                        </div>

                        <div class="rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-[#2c3b53] dark:bg-[#121d2d]">
                            <?= form_permission_modern($permission_user, $permissionL); ?>
                        </div>
                    </div>
                </section>

                <?php if (!empty($custom_fields_html)) { ?>
                    <section class="rounded-xl border border-slate-200 bg-white p-5 dark:border-[#213047] dark:bg-[#0b1220]">
                        <div class="mb-5">
                            <h2 class="text-lg font-semibold text-slate-950 dark:text-white"><?= lang('custom_field') ?></h2>
                            <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">Additional invoice metadata configured for your ERP workflow.</p>
                        </div>
                        <div class="rounded-xl border border-slate-200 bg-slate-50 p-4 dark:border-[#2c3b53] dark:bg-[#121d2d]">
                            <?= $custom_fields_html; ?>
                        </div>
                    </section>
                <?php } ?>
            </div>
        </div>

        <div class="flex flex-col gap-3 border-t border-slate-200 bg-slate-50 px-6 py-4 sm:flex-row sm:items-center sm:justify-between dark:border-[#213047] dark:bg-[#121d2d]">
            <p class="text-xs text-slate-500 dark:text-slate-400">Invoice preview uses the current project billing configuration and selected line items.</p>
            <div class="flex flex-wrap items-center justify-end gap-3">
                <a href="<?= base_url() ?>admin/projects/project_details/<?= $project_info->project_id ?>" class="inline-flex items-center gap-2 rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 transition hover:border-slate-400 hover:text-slate-900 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-200 dark:hover:border-slate-600 dark:hover:text-white">
                    <?= lang('cancel') ?>
                </a>
                <button type="submit" name="save_as_draft" value="1" class="inline-flex items-center gap-2 rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-semibold text-slate-700 transition hover:border-slate-400 hover:text-slate-900 dark:border-slate-700 dark:bg-slate-950 dark:text-slate-200 dark:hover:border-slate-600 dark:hover:text-white">
                    <i data-lucide="clock-3"></i>
                    <?= lang('save_as_draft') ?>
                </button>
                <button type="submit" name="create" value="1" class="inline-flex items-center gap-2 rounded-xl bg-indigo-600 px-5 py-2.5 text-sm font-semibold text-white shadow-sm transition hover:bg-indigo-500">
                    <i data-lucide="check"></i>
                    <?= lang('invoice_project') ?>
                </button>
            </div>
        </div>
    </div>
</form>

<script type="text/javascript">
    function slideToggle($id) {
        $('#quick_state').attr('data-original-title', '<?= lang('view_quick_state') ?>');
        $($id).slideToggle('slow');
    }

    $(document).ready(function () {
        if (typeof init_items_sortable === 'function') {
            init_items_sortable();
        }

        $('#start_recurring').on('click', function () {
            $('#recurring').slideToggle('fast');
            $('#recurring').removeClass('hide hidden');
            $('#recuring_frequency').prop('disabled', false);
        });

        $("#select_all_tasks").on("click", function () {
            $(".tasks_list").prop('checked', $(this).prop('checked'));
        });
        $("#select_all_expense").on("click", function () {
            $(".expense_list").prop('checked', $(this).prop('checked'));
        });

        $('[data-toggle="popover"]').popover();

    });
</script>

