<?= 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);
if (strtotime($invoice_info->due_date) < strtotime(date('Y-m-d')) && $payment_status != lang('fully_paid')) {
    $start = strtotime(date('Y-m-d'));
    $end = strtotime($invoice_info->due_date);
    $days_between = ceil(abs($end - $start) / 86400);
    $overdue = true;
} else {
    $overdue = false;
}

if (is_file(config_item('invoice_logo'))) {
    $img = base_url() . config_item('invoice_logo');
} else {
    $img = base_url() . 'uploads/default_logo.png';
}

$invoice_items = $this->invoice_model->ordered_items_by_id($invoice_info->invoices_id);
$invoice_total = $this->invoice_model->calculate_to('total', $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);
$item_count = !empty($invoice_items) ? count($invoice_items) : 0;
$currency_symbol = !empty($currency->symbol) ? $currency->symbol : null;

$status_badge = $payment_status;
$status_badge_class = 'bg-[#ef5350] text-white';
$status_note = '';
if ($payment_status == lang('fully_paid')) {
    $status_badge_class = 'bg-[#16a34a] text-white';
} elseif ($payment_status == lang('draft')) {
    $status_badge_class = 'bg-[#9ca3af] text-white';
    $status_note = lang('status_as_draft');
} elseif ($payment_status == lang('cancelled')) {
    $status_badge_class = 'bg-[#dc2626] text-white';
} elseif ($payment_status == lang('partially_paid')) {
    $status_badge_class = 'bg-[#f59e0b] text-white';
} elseif ($invoice_info->emailed == 'Yes') {
    $status_badge = lang('sent');
    $status_badge_class = 'bg-[#0ea5e9] text-white';
}

$project_info = null;
if (!empty($invoice_info->project_id)) {
    $project_info = $this->db->where('project_id', $invoice_info->project_id)->get('tbl_project')->row();
}
?>

<link rel="stylesheet" href="<?= base_url('assets/css/tailwind.generated.css') ?>">
<link rel="stylesheet" href="<?= base_url('assets/css/app.css') ?>">
<script src="<?= base_url('assets/vendor/lucide/lucide.min.js') ?>" defer></script>
<style>
    .invoice-accent {
        background-color: #2f315a;
    }

    @media print {
        .invoice-action-wrap {
            display: none !important;
        }

        .invoice-shell {
            border: 0 !important;
            background: #ffffff !important;
            padding: 0 !important;
        }

        #print_invoice {
            border: 0 !important;
            box-shadow: none !important;
            margin-top: 0 !important;
            padding: 0 !important;
        }
    }
</style>

<div class="mx-auto w-full max-w-[1240px] px-3 py-6 sm:px-6">
    <div class="invoice-shell rounded border border-[#d8d8d8] bg-[#f3f3f3] p-4 sm:p-6">
        <div class="invoice-action-wrap mb-4 flex flex-wrap items-center justify-between gap-3">
            <div class="flex flex-wrap items-center gap-2">
                <?php if ($this->invoice_model->get_invoice_cost($invoice_info->invoices_id) > 0) { ?>
                    <div class="relative inline-block text-left">
                        <button id="payBtn" class="inline-flex items-center gap-1 rounded-sm bg-[#eb5757] px-4 py-2 text-sm font-semibold text-white hover:bg-[#d64f4f]">
                            <?= lang('pay_invoice') ?>
                            <i data-lucide="chevron-down" class="h-4 w-4"></i>
                        </button>
                        <div id="payMenu" class="hidden absolute left-0 z-30 mt-1.5 w-56 overflow-hidden rounded-sm border border-[#d8d8d8] bg-white py-1 shadow-lg">
                            <?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));
                                if ($status == 'active' && $invoice_info->$allow_gateway == 'Yes') {
                                    $modal = '';
                                    if ($payment->modal == 'Yes') {
                                        $modal = 'data-toggle="modal" data-target="#myModal"';
                                    }
                            ?>
                                    <a <?= $modal ?> href="<?= base_url($payment->link . '/pay' . '/' . $invoice_info->invoices_id) ?>" class="block px-3 py-2 text-sm text-[#0f172a] hover:bg-slate-100">
                                        <?= lang($payment->gateway_name) ?>
                                    </a>
                            <?php
                                }
                            }
                            ?>
                        </div>
                    </div>
                <?php } ?>
            </div>
            <div class="flex items-center gap-1.5">
                <a href="<?= base_url() ?>frontend/pdf_invoice/<?= $invoice_info->invoices_id ?>" class="inline-flex h-8 w-8 items-center justify-center bg-[#22c55e] text-white hover:bg-[#16a34a]" title="<?= lang('pdf') ?>">
                    <i data-lucide="file-text" class="h-4 w-4"></i>
                </a>
                <button type="button" onclick="print_invoice('print_invoice')" class="inline-flex h-8 w-8 items-center justify-center bg-[#ef4444] text-white hover:bg-[#dc2626]" title="<?= lang('print') ?: 'Print' ?>">
                    <i data-lucide="printer" class="h-4 w-4"></i>
                </button>
            </div>
        </div>

        <?php if ($overdue) : ?>
            <div class="mb-6 border border-[#ef7f7f] bg-[#ef7f7f] px-3 py-2 text-sm text-white">
                <span class="inline-flex items-center gap-1">
                    <i data-lucide="alert-triangle" class="h-4 w-4"></i>
                    <?= lang('invoice_overdue') . '! ' . lang('by') . ' ' . $days_between . ' ' . lang('days') ?>
                </span>
            </div>
        <?php endif; ?>

        <div id="print_invoice" class="border border-[#e1e1e1] bg-white p-6">
            <div class="grid grid-cols-1 gap-6 md:grid-cols-2 md:items-start">
                <div class="flex items-start">
                    <img class="h-24 w-56 object-contain sm:h-28 sm:w-64" src="<?= $img ?>" alt="logo">
                </div>
                <div class="text-left text-sm text-[#001b44] md:text-right">
                    <h3 class="text-xl font-semibold sm:text-3xl"><?= lang('invoice') . ' : ' . $invoice_info->reference_no ?></h3>
                    <div class="mt-2 space-y-1">
                        <p><?= $language_info['invoice_date'] ?> : <?= display_date($invoice_info->invoice_date); ?></p>
                        <p><?= $language_info['due_date'] ?> : <?= display_date($invoice_info->due_date); ?></p>
                        <?php if (!empty($invoice_info->user_id)) { ?>
                            <p><?= lang('sales') . ' ' . lang('agent') ?>: <?= fullname($invoice_info->user_id); ?></p>
                        <?php } ?>
                        <p>
                            <?= lang('payment_status') ?>:
                            <span class="ml-1 inline-block rounded-sm px-2 py-0.5 text-[11px] font-semibold <?= $status_badge_class ?>">
                                <?= $status_badge ?>
                            </span>
                        </p>
                        <?php if (!empty($project_info)) { ?>
                            <p><?= lang('project') ?>: <?= html_escape((string) $project_info->project_name) ?></p>
                        <?php } ?>
                        <?php if (!empty($status_note)) { ?>
                            <p class="rounded-sm bg-[#fef3c7] px-2 py-1 text-[#9a3412]"><?= $status_note ?></p>
                        <?php } ?>
                        <?php
                        $show_custom_fields = custom_form_label(9, $invoice_info->invoices_id);
                        if (!empty($show_custom_fields)) {
                            foreach ($show_custom_fields as $c_label => $v_fields) {
                                if (!empty($v_fields)) {
                        ?>
                                    <p><strong><?= $c_label ?>:</strong> <?= $v_fields; ?></p>
                        <?php
                                }
                            }
                        }
                        ?>
                    </div>
                </div>
            </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
            <div>
                <div class="bg-muted px-3 py-2 rounded text-sm font-medium mb-2 text-muted-foreground"><?= lang('our_info') ?>:</div>
                <div class="text-sm text-foreground">
                    <h4 class="font-semibold mb-1"><?= (config_item('company_legal_name_' . $client_lang) ? config_item('company_legal_name_' . $client_lang) : config_item('company_legal_name')) ?></h4>
                    <?= (config_item('company_address_' . $client_lang) ? config_item('company_address_' . $client_lang) : config_item('company_address')) ?><br>
                    <?= (config_item('company_city_' . $client_lang) ? config_item('company_city_' . $client_lang) : config_item('company_city')) ?>, <?= config_item('company_zip_code') ?><br>
                    <?= (config_item('company_country_' . $client_lang) ? config_item('company_country_' . $client_lang) : config_item('company_country')) ?><br>
                    <?= $language_info['phone'] ?>: <?= config_item('company_phone') ?><br>
                    <?= lang('vat_number') ?>: <?= config_item('company_vat') ?>
                </div>
            </div>
            <div>
                <div class="bg-muted px-3 py-2 rounded text-sm font-medium mb-2 text-muted-foreground"><?= lang('customer') ?>:</div>
                <div class="text-sm text-foreground">
                    <?php
                    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;
                    } else {
                        $client_name = '-';
                        $address = '-';
                        $city = '-';
                        $zipcode = '-';
                        $country = '-';
                        $phone = '-';
                    }
                    ?>
                    <h4 class="font-semibold mb-1"><?= $client_name ?></h4>
                    <?= $address ?><br>
                    <?= $city ?>, <?= $zipcode ?><br>
                    <?= $country ?><br>
                    <?= $language_info['phone'] ?>: <?= $phone ?><br>
                    <?php if (!empty($client_info->vat)) { ?>
                    <?= lang('vat_number') ?>: <?= $client_info->vat ?><br>
                    <?php } ?>
                </div>
            </div>
        </div>

        <div class="overflow-x-auto mt-6">
            <table class="w-full table-auto border-collapse">
                <thead class="bg-muted text-sm text-muted-foreground">
                    <tr>
                        <th class="text-left p-3 border-b"><?= $language_info['items'] ?></th>
                        <?php $invoice_view = config_item('invoice_view'); if (!empty($invoice_view) && $invoice_view == '2') { ?>
                        <th class="text-left p-3 border-b"><?= $language_info['hsn_code'] ?></th>
                        <?php } ?>
                        <?php
                        $qty_heading = $language_info['qty'];
                        if (isset($invoice_info) && $invoice_info->show_quantity_as == 'hours' || isset($hours_quantity)) {
                            $qty_heading = lang('hours');
                        } else if (isset($invoice_info) && $invoice_info->show_quantity_as == 'qty_hours') {
                            $qty_heading = lang('qty') . '/' . lang('hours');
                        }
                        ?>
                        <th class="text-left p-3 border-b"><?php echo $qty_heading; ?></th>
                        <th class="text-right p-3 border-b"><?= $language_info['price'] ?></th>
                        <th class="text-right p-3 border-b"><?= $language_info['tax'] ?></th>
                        <th class="text-right p-3 border-b"><?= $language_info['total'] ?></th>
                    </tr>
                </thead>
                <tbody class="text-sm text-foreground">
                    <?php
                    if (!empty($invoice_items)) :
                        foreach ($invoice_items as $key => $v_item) :
                            $item_name = $v_item->item_name ? $v_item->item_name : $v_item->item_desc;
                            $item_tax_name = !empty($v_item->item_tax_name) ? json_decode($v_item->item_tax_name) : [];
                    ?>
                    <tr class="align-top">
                        <td class="p-3 align-top"><strong class="block text-foreground"><?= $item_name ?></strong>
                            <?= nl2br($v_item->item_desc) ?>
                        </td>
                        <?php if (!empty($invoice_view) && $invoice_view == '2') { ?>
                        <td class="p-3 align-top"><?= $v_item->hsn_code ?></td>
                        <?php } ?>
                        <td class="p-3 align-top"><?= $v_item->quantity . ' ' . $v_item->unit ?></td>
                        <td class="p-3 text-right align-top"><?= display_money($v_item->unit_cost) ?></td>
                        <td class="p-3 text-right align-top"><?php
                                    if (!empty($item_tax_name)) {
                                        foreach ($item_tax_name as $v_tax_name) {
                                            $i_tax_name = explode('|', $v_tax_name);
                                            echo '<div class="text-right">' . $i_tax_name[0] . ' (' . $i_tax_name[1] . ' %) ' . display_money($v_item->total_cost / 100 * $i_tax_name[1]) . '</div>';
                                        }
                                    }
                                    ?></td>
                        <td class="p-3 text-right align-top"><?= display_money($v_item->total_cost) ?></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php else : ?>
                    <tr>
                        <td colspan="6" class="p-3 text-center"><?= lang('nothing_to_display') ?></td>
                    </tr>
                    <?php endif ?>

                </tbody>
            </table>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-8">
            <div>
                <div class="bg-card/80 p-4 rounded text-sm text-foreground">
                    <?= $invoice_info->notes ?>
                </div>
            </div>
            <div>
                <div class="bg-card/80 p-4 rounded text-sm text-foreground space-y-3">
                    <div class="flex justify-between"><span><?= $language_info['sub_total'] ?></span><span class="font-medium"><?= display_money($this->invoice_model->calculate_to('invoice_cost', $invoice_info->invoices_id)); ?></span></div>
                    <?php if ($invoice_info->discount_total > 0) : ?>
                    <div class="flex justify-between"><span><?= $language_info['discount'] ?> (<?php echo $invoice_info->discount_percent; ?>%)</span><span><?= display_money($this->invoice_model->calculate_to('discount', $invoice_info->invoices_id)); ?></span></div>
                    <?php endif ?>
                    <?php
                    $tax_info = !empty($invoice_info->total_tax) ? json_decode($invoice_info->total_tax) : null;
                    $tax_total = 0;
                    if (is_numeric($tax_info)) {
                        $tax_total = (float) $tax_info;
                    } elseif (is_object($tax_info)) {
                        $tax_name = !empty($tax_info->tax_name) ? $tax_info->tax_name : array();
                        $total_tax = !empty($tax_info->total_tax) ? $tax_info->total_tax : array();
                        if (!empty($tax_name)) {
                            foreach ($tax_name as $t_key => $v_tax_info) {
                                $tax = explode('|', $v_tax_info);
                                $line_tax = isset($total_tax[$t_key]) ? (float) $total_tax[$t_key] : 0;
                                $tax_total += $line_tax;
                    ?>
                    <div class="flex justify-between"><span><?= $tax[0] . ' (' . $tax[1] . ' %)' ?></span><span><?= display_money($line_tax); ?></span></div>
                    <?php }
                        }
                    } ?>
                    <?php if ($tax_total > 0) : ?>
                    <div class="flex justify-between"><span><?= $language_info['total'] . ' ' . $language_info['tax'] ?></span><span><?= display_money($tax_total); ?></span></div>
                    <?php endif ?>
                    <?php if ($invoice_info->adjustment > 0) : ?>
                    <div class="flex justify-between"><span><?= $language_info['adjustment'] ?></span><span><?= display_money($invoice_info->adjustment); ?></span></div>
                    <?php endif ?>
                    <div class="flex justify-between text-lg font-semibold"><span><?= $language_info['total'] ?></span><span><?= display_money($this->invoice_model->calculate_to('total', $invoice_info->invoices_id), $currency->symbol); ?></span></div>

                    <?php
                    $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 ($paid_amount > 0) {
                    ?>
                    <div class="flex justify-between"><span><?= $language_info['paid_amount'] ?></span><span><?= display_money($paid_amount, $currency->symbol); ?></span></div>
                    <div class="flex justify-between text-xl font-bold text-red-600"><span><?= $language_info['total_due'] ?></span><span><?= display_money($invoice_due, $currency->symbol); ?></span></div>
                    <?php } ?>

                    <?php if (config_item('amount_to_words') == 'Yes') { ?>
                    <div class="text-right text-sm"><strong><?= lang('num_word') ?>:</strong> <?= number_to_word($invoice_info->client_id, $invoice_due); ?></div>
                    <?php } ?>
                </div>
            </div>
        </div>

    </div>

    <?= !empty($invoice_view) && $invoice_view > 0 ? $this->gst->summary($invoice_items) : ''; ?>

</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') { ?>
<!-- START STRIPE PAYMENT -->
<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>
<!-- END STRIPE CHECKOUT -->
<?php } ?>

<script type="text/javascript">
(function () {
    var payBtn = document.getElementById('payBtn');
    var payMenu = document.getElementById('payMenu');

    if (payBtn && payMenu) {
        payBtn.addEventListener('click', function (event) {
            event.preventDefault();
            event.stopPropagation();
            payMenu.classList.toggle('hidden');
        });

        document.addEventListener('click', function (event) {
            if (payMenu.contains(event.target) || payBtn.contains(event.target)) {
                return;
            }
            payMenu.classList.add('hidden');
        });
    }

    window.print_invoice = function (targetId) {
        var printNode = document.getElementById(targetId);
        if (!printNode) {
            return;
        }

        var popup = window.open('', '_blank', 'width=1200,height=800');
        if (!popup) {
            return;
        }

        var styles = '';
        var styleNodes = document.querySelectorAll('link[rel="stylesheet"], style');
        for (var i = 0; i < styleNodes.length; i++) {
            styles += styleNodes[i].outerHTML;
        }

        popup.document.open();
        popup.document.write('<!DOCTYPE html><html><head><title>' + document.title + '</title>' + styles + '</head><body>' + printNode.outerHTML + '</body></html>');
        popup.document.close();
        popup.onload = function () {
            popup.focus();
            popup.print();
            popup.close();
        };
    };

    if (window.lucide && typeof window.lucide.createIcons === 'function') {
        window.lucide.createIcons();
    } else {
        window.addEventListener('load', function () {
            if (window.lucide && typeof window.lucide.createIcons === 'function') {
                window.lucide.createIcons();
            }
        });
    }
})();
</script>
