<div class="invoice-modern">
<?= message_box('success') ?>
<?= message_box('error') ?>

<?php
$client_info = $this->invoice_model->check_by(array('client_id' => $invoice_info->client_id), 'tbl_client');
if (!empty($client_info)) {
    $currency = $this->invoice_model->client_currency_symbol($invoice_info->client_id);
    $client_lang = $client_info->language;
} else {
    $client_lang = 'english';
    $currency = $this->invoice_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
}
unset($this->lang->is_loaded[5]);
$language_info = $this->lang->load('sales_lang', $client_lang, true, false, '', true);
$allow_customer_edit_amount = config_item('allow_customer_edit_amount');

$payment_status = $this->invoice_model->get_payment_status($invoice_info->invoices_id);
$status_value = strtolower((string) $payment_status);
$status_class = 'bg-slate-100 text-slate-700 border-slate-200';
if ($status_value === strtolower(lang('fully_paid')) || $status_value === strtolower(lang('paid'))) {
    $status_class = 'bg-emerald-50 text-emerald-700 border-emerald-200';
} elseif ($status_value === strtolower(lang('draft'))) {
    $status_class = 'bg-slate-100 text-slate-700 border-slate-200';
} elseif ($status_value === strtolower(lang('partially_paid'))) {
    $status_class = 'bg-amber-50 text-amber-700 border-amber-200';
} elseif ($status_value === strtolower(lang('cancelled'))) {
    $status_class = 'bg-rose-50 text-rose-700 border-rose-200';
} elseif ($status_value === strtolower(lang('sent'))) {
    $status_class = 'bg-blue-50 text-blue-700 border-blue-200';
}

$overdue_message = '';
if (safe_strtotime($invoice_info->due_date) < safe_strtotime(date('Y-m-d')) && $payment_status != lang('fully_paid')) {
    $start = safe_strtotime(date('Y-m-d'));
    $end = safe_strtotime($invoice_info->due_date);
    $days_between = ceil(abs($end - $start) / 86400);
    $overdue_message = lang('invoice_overdue') . ' ' . lang('by') . ' ' . $days_between . ' ' . lang('days');
}

$all_items = $this->invoice_model->ordered_items_by_id($invoice_info->invoices_id);
$paid_amount = $this->invoice_model->calculate_to('paid_amount', $invoice_info->invoices_id);
$invoice_due = $this->invoice_model->calculate_to('invoice_due', $invoice_info->invoices_id);

if (!empty($client_info)) {
    $client_name = $client_info->name;
    $address = $client_info->address;
    $city = $client_info->city;
    $zipcode = $client_info->zipcode;
    $country = $client_info->country;
    $phone = $client_info->phone;
    $vat = $client_info->vat;
} else {
    $client_name = '-';
    $address = '-';
    $city = '-';
    $zipcode = '-';
    $country = '-';
    $phone = '-';
    $vat = '';
}

$custom_fields = custom_form_label(9, $invoice_info->invoices_id);
$custom_field_markup = '';
if (!empty($custom_fields)) {
    foreach ($custom_fields as $c_label => $v_fields) {
        if (!empty($v_fields)) {
            $custom_field_markup .= '<div>' . html_escape($c_label) . ': ' . html_escape($v_fields) . '</div>';
        }
    }
}

$sales_info = (object) array(
    'reference_no' => $invoice_info->reference_no,
    'status' => $payment_status,
    'invoice_date' => $invoice_info->invoice_date,
    'due_date' => $invoice_info->due_date,
    'start_date' => $language_info['invoice_date'] . ': ' . display_date($invoice_info->invoice_date),
    'end_date' => $language_info['due_date'] . ': ' . display_date($invoice_info->due_date),
    'sales_agent' => !empty($invoice_info->user_id) ? lang('sales') . ' ' . lang('agent') . ': ' . fullname($invoice_info->user_id) : null,
    'custom_field' => $custom_field_markup,
    'client_id' => $invoice_info->client_id,
    'name' => $client_name,
    'address' => $address,
    'city' => $city,
    'zipcode' => $zipcode,
    'country' => $country,
    'phone' => $phone,
    'vat' => $vat,
    'notes' => $invoice_info->notes,
    'sub_total' => $this->invoice_model->calculate_to('invoice_cost', $invoice_info->invoices_id),
    'discount' => $this->invoice_model->calculate_to('discount', $invoice_info->invoices_id),
    'discount_percent' => $invoice_info->discount_percent,
    'total_tax' => $invoice_info->total_tax,
    'adjustment' => $invoice_info->adjustment,
    'total' => $this->invoice_model->calculate_to('total', $invoice_info->invoices_id),
    'overdue_days' => $overdue_message,
    'project_id' => $invoice_info->project_id,
);

$text_notice = '';
if ($payment_status == lang('draft')) {
    $text_notice = lang('status_as_draft');
}
?>

<div class="space-y-6">
    <div class="rounded-2xl border border-border bg-card p-6 shadow-sm">
        <div class="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
            <div class="space-y-2">
                <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('invoice') ?></p>
                <div class="flex flex-wrap items-center gap-3">
                    <h1 class="text-2xl font-semibold text-foreground">#<?= html_escape($invoice_info->reference_no) ?></h1>
                    <span class="inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold <?= $status_class ?>">
                        <?= html_escape($payment_status) ?>
                    </span>
                    <span class="inline-flex items-center rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-muted-foreground">
                        <?= display_date($invoice_info->invoice_date) ?>
                    </span>
                    <span class="inline-flex items-center rounded-full border border-border px-2.5 py-1 text-xs font-semibold text-muted-foreground">
                        <?= lang('due_date') ?>: <?= display_date($invoice_info->due_date) ?>
                    </span>
                </div>
                <?php if (!empty($invoice_info->project_id)) {
                    $project_info = $this->db->where('project_id', $invoice_info->project_id)->get('tbl_project')->row(); ?>
                    <div class="text-sm text-muted-foreground">
                        <?= lang('project') ?>:
                        <a href="<?= base_url('client/projects/project_details/' . $invoice_info->project_id) ?>" class="text-primary hover:underline">
                            <?= html_escape($project_info->project_name) ?>
                        </a>
                    </div>
                <?php } ?>
            </div>
            <div class="flex flex-wrap items-center gap-2">
                <?php if ($this->invoice_model->get_invoice_cost($invoice_info->invoices_id) > 0) { ?>
                    <a href="<?= base_url() ?>client/invoice/manage_invoice/invoice_history/<?= $invoice_info->invoices_id ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted">
                        <i data-lucide="history" class="h-4 w-4"></i>
                        <?= lang('invoice_history') ?>
                    </a>
                    <div class="relative" data-dropdown>
                        <button type="button" data-dropdown-toggle="pay-invoice" class="inline-flex items-center gap-2 rounded-lg bg-rose-600 px-3 py-2 text-xs font-semibold text-white shadow-sm hover:bg-rose-500">
                            <i data-lucide="credit-card" class="h-4 w-4"></i>
                            <?= lang('pay_invoice') ?>
                        </button>
                        <div id="pay-invoice" data-dropdown-menu class="hidden absolute right-0 mt-2 w-56 rounded-xl border border-border bg-card shadow-lg p-2 z-30">
                            <?php
                            $all_payment = get_result('tbl_online_payment');
                            foreach ($all_payment as $key => $payment) {
                                $status = $this->config->item(slug_it(strtolower($payment->gateway_name)) . '_status');
                                $allow_gateway = 'allow_' . slug_it(strtolower($payment->gateway_name));
                                $is_allowed = isset($invoice_info->$allow_gateway) && $invoice_info->$allow_gateway == 'Yes';
                                if ($status == 'active' && $is_allowed) {
                                    $payment_url = base_url($payment->link . '/pay/' . $invoice_info->invoices_id);
                                    $modal_attrs = '';
                                    if ($payment->modal == 'Yes') {
                                        $modal_attrs = ' data-modal-url="' . html_escape($payment_url) . '" data-modal-title="' . html_escape(lang($payment->gateway_name)) . '" data-modal-size="md"';
                                    }
                                    ?>
                                    <a<?= $modal_attrs ?> href="<?= html_escape($payment_url) ?>" class="block px-3 py-2 text-xs text-foreground hover:bg-muted rounded-lg" title="<?= lang($payment->gateway_name) ?>">
                                        <?= lang($payment->gateway_name) ?>
                                    </a>
                                <?php }
                            } ?>
                        </div>
                    </div>
                <?php } ?>
                <a href="<?= base_url() ?>client/invoice/pdf_invoice/<?= $invoice_info->invoices_id ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted">
                    <i data-lucide="file-text" class="h-4 w-4"></i>
                    PDF
                </a>
                <a href="#" onclick="print_sales_details('sales_details'); return false;" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted">
                    <i data-lucide="printer" class="h-4 w-4"></i>
                    <?= lang('print') ?>
                </a>
            </div>
        </div>
        <?php if (!empty($text_notice)) { ?>
            <div class="mt-4 rounded-lg border border-amber-200 bg-amber-50 p-3 text-sm text-amber-700">
                <?= $text_notice ?>
            </div>
        <?php } ?>
    </div>

    <?php
    $this->load->view('admin/common/sales_details_modern', array(
        'sales_info' => $sales_info,
        'all_items' => $all_items,
        'paid_amount' => $paid_amount,
        'invoice_due' => $invoice_due,
        'payment_status' => $payment_status,
    ));
    ?>

    <?php
    $all_payment_info = $this->db->where('invoices_id', $invoice_info->invoices_id)->get('tbl_payments')->result();
    if (!empty($all_payment_info)) {
        $edited = isset($edited) ? $edited : null;
        $deleted = isset($deleted) ? $deleted : null;
        $can_edit = isset($can_edit) ? $can_edit : null;
        $can_delete = isset($can_delete) ? $can_delete : null;
        ?>
        <div class="rounded-2xl border border-border bg-card shadow-sm">
            <div class="border-b border-border px-4 py-4">
                <div class="text-sm font-semibold text-foreground"><?= lang('payment') . ' ' . lang('details') ?></div>
            </div>
            <div class="table-responsive p-4">
                <table class="table table-striped DataTables" id="DataTables" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th><?= lang('transaction_id') ?></th>
                            <th><?= lang('payment_date') ?></th>
                            <th><?= lang('amount') ?></th>
                            <th><?= lang('payment_mode') ?></th>
                            <?php if (!empty($edited) || !empty($deleted)) { ?>
                                <th class="hidden-print"><?= lang('action') ?></th>
                            <?php } ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        foreach ($all_payment_info as $v_payments_info) {
                            if (is_numeric($v_payments_info->payment_method)) {
                                $v_payments_info->method_name = get_any_field('tbl_payment_methods', array('payment_methods_id' => $v_payments_info->payment_method), 'method_name');
                            } else {
                                $v_payments_info->method_name = $v_payments_info->payment_method;
                            }
                            ?>
                            <tr>
                                <td>
                                    <a href="<?= base_url() ?>client/invoice/manage_invoice/payments_details/<?= $v_payments_info->payments_id ?>">
                                        <?= html_escape($v_payments_info->trans_id); ?>
                                    </a>
                                </td>
                                <td>
                                    <a href="<?= base_url() ?>client/invoice/manage_invoice/payments_details/<?= $v_payments_info->payments_id ?>">
                                        <?= display_date($v_payments_info->payment_date); ?>
                                    </a>
                                </td>
                                <td><?= display_money($v_payments_info->amount, $currency->symbol) ?></td>
                                <td><?= !empty($v_payments_info->method_name) ? $v_payments_info->method_name : '-' ?></td>
                                <?php if (!empty($edited) || !empty($deleted)) { ?>
                                    <td>
                                        <?php if (!empty($can_edit) && !empty($edited)) { ?>
                                            <?= btn_edit('client/invoice/all_payments/' . $v_payments_info->payments_id) ?>
                                        <?php }
                                        if (!empty($can_delete) && !empty($deleted)) { ?>
                                            <?= btn_delete('client/invoice/delete/delete_payment/' . $v_payments_info->payments_id) ?>
                                        <?php } ?>
                                        <a data-toggle="tooltip" data-placement="top" href="<?= base_url() ?>client/invoice/send_payment/<?= $v_payments_info->payments_id . '/' . $v_payments_info->amount ?>" title="<?= lang('send_email') ?>" class="btn btn-xs btn-success">
                                            <i data-lucide="mail"></i>
                                        </a>
                                        <a data-toggle="tooltip" data-placement="top" href="<?= base_url() ?>client/invoice/payments_pdf/<?= $v_payments_info->payments_id ?>" title="<?= lang('pdf') ?>" class="btn btn-xs btn-warning">
                                            <i data-lucide="file-text"></i>
                                        </a>
                                    </td>
                                <?php } ?>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php } ?>
</div>

<?php if ($invoice_info->allow_braintree == 'Yes') { ?>
    <script src="https://js.braintreegateway.com/js/braintree-2.21.0.min.js"></script>
<?php } ?>

<?php if ($invoice_info->allow_stripe == 'Yes') { ?>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://checkout.stripe.com/checkout.js"></script>
<?php } ?>

<textarea class="hidden" style="display:none" data-client-invoice-print-html><?= html_escape(isset($invoice_print_html) ? $invoice_print_html : '') ?></textarea>
<script>
    document.addEventListener('click', function(event) {
        var button = event.target.closest('[data-copy-target]');
        if (!button) return;
        var selector = button.getAttribute('data-copy-target');
        var input = document.querySelector(selector);
        if (!input) return;
        input.select();
        input.setSelectionRange(0, input.value.length);
        try {
            document.execCommand('copy');
        } catch (e) {}
    });

    window.print_sales_details = function(salesId) {
        var textarea = document.querySelector('[data-client-invoice-print-html]');
        var fallback = document.getElementById(salesId);
        var printHtml = (textarea ? textarea.value : '') || (fallback ? fallback.outerHTML : '');
        if (!printHtml) return false;

        var printWindow = window.open('', 'PRINT', 'height=900,width=1200');
        if (!printWindow) {
            window.print();
            return false;
        }

        printWindow.document.open();
        printWindow.document.write(printHtml);
        printWindow.document.close();

        var printed = false;
        var doPrint = function() {
            if (printed || printWindow.closed) return;
            printed = true;
            printWindow.focus();
            printWindow.print();
            printWindow.close();
        };
        printWindow.onload = function() {
            printWindow.setTimeout(doPrint, 350);
        };
        printWindow.setTimeout(doPrint, 900);
        return false;
    };
</script>
</div>

