<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
$settings = Branding::settings();
$vatPercentage = (float)($settings['vat_percentage'] ?? 17.5);
$vatRate = $vatPercentage / 100;
$profitPercentage = (float)($settings['profit_percentage'] ?? 30.0);
$profitRate = $profitPercentage / 100;
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Invoice.php';

$database = new Database();
$conn = $database->getConnection();

$branch = new Branch($conn);
$auth = new Auth($conn);


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);

$invoice = new Invoice($conn, $logger);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$userRole = $auth->getUserRole($_SESSION['user_id']);
if (!in_array($userRole, ['branch', 'warehouse', 'sales'])) {
    header('Location: ../../unauthorized.php');
    exit();
}

$branchId = $auth->getUserBranch($_SESSION['user_id']);
if (!$branchId) {
    die("Error: You are not assigned to any branch.");
}

$branchDetails = $branch->getBranchById($branchId);
$cashierName = $auth->getUserName($_SESSION['user_id']);
$invoiceNumber = 'INV' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);

$message = '';
$formData = [
    'customer_name' => '',
    'customer_contact' => '',
    'validity_days' => 30,
    'notes' => '',
    'items' => [],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_invoice'])) {
    $customerName = trim($_POST['customer_name'] ?? '');
    $customerContact = trim($_POST['customer_contact'] ?? '');
    $validityDays = (int)($_POST['validity_days'] ?? 30);
    $notes = trim($_POST['notes'] ?? '');
    // Clamp against a tampered/absurd hidden quantity field driving an unbounded loop below.
    $quantity = min(max((int)($_POST['quantity'] ?? 0), 0), 500);

    $items = [];
    for ($i = 1; $i <= $quantity; $i++) {
        $items[] = [
            'qty' => (int)($_POST["item_qty_$i"] ?? 0),
            'item_name' => trim($_POST["item_name_$i"] ?? ''),
            'unit_price' => (float)($_POST["unit_price_$i"] ?? 0)
        ];
    }

    $formData = [
        'customer_name' => $customerName,
        'customer_contact' => $customerContact,
        'validity_days' => $validityDays,
        'notes' => $notes,
        'items' => $items,
    ];

    $failureReason = null;
    if (empty($customerName) || empty($customerContact) || $quantity <= 0) {
        $failureReason = 'Please fill in all required fields.';
    } else {
        foreach ($items as $index => $item) {
            if ($item['qty'] <= 0 || empty($item['item_name']) || $item['unit_price'] <= 0) {
                $failureReason = 'Please provide valid item details for item ' . ($index + 1) . '.';
                break;
            }
        }
    }

    if ($failureReason === null) {
        // The server-recalculated total is always the source of truth (client-submitted
        // totals are display-only), so large/rounded amounts are never falsely rejected.
        $calculatedSubtotal = 0;
        foreach ($items as $item) {
            $calculatedSubtotal += $item['qty'] * $item['unit_price'];
        }
        $calculatedSubtotal = round($calculatedSubtotal, 2);
        $calculatedSurtax = round($calculatedSubtotal * $vatRate, 2);
        $calculatedTotal = round($calculatedSubtotal + $calculatedSurtax, 2);

        $maxRetries = 3;
        $retryCount = 0;
        do {
            $invoiceNumber = 'INV' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            $result = $invoice->createInvoice(
                $branchId,
                $_SESSION['user_id'],
                $invoiceNumber,
                $customerName,
                $customerContact,
                $items,
                $calculatedSubtotal,
                $calculatedSurtax,
                $calculatedTotal,
                $validityDays,
                $notes
            );
            $retryCount++;
        } while (!$result['success'] && strpos($result['message'], 'Duplicate entry') !== false && $retryCount < $maxRetries);

        if ($result['success']) {
            $_SESSION['invoice_data'] = [
                'invoice_id' => $result['invoice_id'],
                'invoice_number' => $invoiceNumber,
                'customer_name' => $customerName,
                'customer_contact' => $customerContact,
                'validity_days' => $validityDays,
                'notes' => $notes,
                'items' => $items,
                'subtotal' => $calculatedSubtotal,
                'surtax' => $calculatedSurtax,
                'grand_total' => $calculatedTotal,
                'created_at' => date('Y-m-d H:i:s'),
                'created_by_name' => $cashierName,
                'branch_name' => $branchDetails['branch_name'] ?? $companyName,
                'branch_address' => $branchDetails['branch_address'] ?? '',
                'branch_phone' => $branchDetails['branch_phone'] ?? '',
                'branch_email' => $branchDetails['branch_email'] ?? '',
                'branch_website' => $branchDetails['branch_website'] ?? ''
            ];
            header('Location: invoice_receipt.php');
            exit();
        } else {
            $failureReason = 'Failed to create invoice: ' . $result['message'];
        }
    }

    if ($failureReason !== null) {
        // Never lose the user's work: persist whatever was entered as a draft they
        // can reopen and finish, instead of wiping the form on error.
        $draftSubtotal = 0;
        foreach ($items as $item) {
            $draftSubtotal += (float)($item['qty'] ?? 0) * (float)($item['unit_price'] ?? 0);
        }
        $draftSubtotal = round($draftSubtotal, 2);
        $draftSurtax = round($draftSubtotal * $vatRate, 2);
        $draftTotal = round($draftSubtotal + $draftSurtax, 2);

        $draftRetries = 0;
        do {
            $draftInvoiceNumber = 'INV' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            $draftResult = $invoice->saveDraft(
                $branchId,
                $_SESSION['user_id'],
                $draftInvoiceNumber,
                $customerName,
                $customerContact,
                $items,
                $draftSubtotal,
                $draftSurtax,
                $draftTotal,
                $validityDays,
                $notes
            );
            $draftRetries++;
        } while (!$draftResult['success'] && strpos($draftResult['message'], 'Duplicate entry') !== false && $draftRetries < 3);

        if ($draftResult['success']) {
            header('Location: edit_invoice.php?invoice_id=' . $draftResult['invoice_id'] . '&draft=1&error=' . urlencode($failureReason . ' Your invoice was saved as a draft so you can review and complete it.'));
            exit();
        } else {
            $message = '<div class="alert alert-danger">' . htmlspecialchars($failureReason) . '</div>';
        }
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        /* ── Google Font (matches create_order.php / edit_sale.php / order_details.php) ── */
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');

        *, *::before, *::after { box-sizing: border-box; }
        :root {
            --brand:          #4F46E5;
            --brand-dark:     #3730A3;
            --brand-light:    #EEF2FF;
            --brand-ring:     rgba(79,70,229,.18);

            --success:        #059669;
            --success-bg:     #ECFDF5;
            --success-border: #A7F3D0;
            --success-ring:   rgba(5,150,105,.18);
            --danger:         #DC2626;
            --danger-bg:      #FEF2F2;
            --danger-border:  #FECACA;
            --warning:        #D97706;
            --warning-bg:     #FFFBEB;
            --info:           #0284C7;
            --info-bg:        #E0F2FE;

            --n900: #0F172A; --n800: #1E293B; --n700: #334155; --n600: #475569;
            --n500: #64748B; --n400: #94A3B8; --n300: #CBD5E1; --n200: #E2E8F0;
            --n100: #F1F5F9; --n50:  #F8FAFC; --white: #FFFFFF;

            --topbar-h: 58px;
            --r-sm: 6px; --r: 10px; --r-lg: 14px;
            --s2: 0 1px 3px rgba(0,0,0,.07), 0 1px 2px rgba(0,0,0,.04);
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            color: var(--n800);
            background: var(--n100);
            -webkit-font-smoothing: antialiased;
        }

        /* ── Top Bar ─────────────────────────────────── */
        .pos-topbar {
            display: flex; align-items: center; justify-content: space-between;
            background: var(--n900); color: var(--white);
            min-height: var(--topbar-h);
            position: sticky; top: 0; z-index: 300;
            border-bottom: 3px solid var(--brand);
            padding: 10px 20px; margin: 0 -15px 24px; gap: 12px; flex-wrap: wrap;
        }
        .pos-topbar-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
        .pos-topbar .brand-icon {
            width: 34px; height: 34px; border-radius: var(--r-sm);
            background: var(--brand); display: flex; align-items: center;
            justify-content: center; font-size: 15px; color: #fff; flex-shrink: 0;
        }
        .pos-topbar-title-wrap { line-height: 1.25; min-width: 0; }
        .pos-topbar-title { font-size: 1rem; font-weight: 700; color: var(--white); display: block; }
        .pos-topbar-sub { font-size: .76rem; color: var(--n400); }
        .pos-topbar-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }

        /* ── Page wrap ───────────────────────────────── */
        .page-wrap { max-width: 900px; margin: 0 auto 60px; padding: 0 5px; }

        /* ── Letterhead strip (company details, compact) ── */
        .letterhead {
            background: var(--white); border-radius: var(--r); border: 1px solid var(--n200);
            box-shadow: var(--s2); padding: 16px 20px; margin-bottom: 18px;
            display: flex; align-items: center; gap: 14px; flex-wrap: wrap;
        }
        .letterhead img { max-height: 40px; flex-shrink: 0; }
        .letterhead-name { font-size: 1rem; font-weight: 800; color: var(--n900); letter-spacing: -.01em; }
        .letterhead-detail { font-size: .74rem; color: var(--n500); line-height: 1.5; }

        /* ── Section card ────────────────────────────── */
        .pos-card {
            background: var(--white); border-radius: var(--r);
            padding: 18px 20px; box-shadow: var(--s2);
            border: 1px solid var(--n200); margin-bottom: 18px;
        }
        .pos-card-title {
            display: flex; align-items: center; gap: 8px;
            font-size: .95rem; font-weight: 700; color: var(--n800);
            margin-bottom: 16px;
        }
        .pos-card-title .icon-badge {
            width: 26px; height: 26px; border-radius: 50%;
            background: var(--brand-light); color: var(--brand);
            display: flex; align-items: center; justify-content: center;
            font-size: .72rem; flex-shrink: 0;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 18px;
        }
        .form-group { display: flex; flex-direction: column; }
        .form-group.full-width { grid-column: 1 / -1; }
        .form-label {
            font-size: .72rem; font-weight: 700; color: var(--n500);
            text-transform: uppercase; letter-spacing: .04em; margin-bottom: 6px;
            display: flex; align-items: center; gap: 6px;
        }
        .required { color: var(--danger); }

        .form-control, .item-input {
            padding: 10px 14px; border: 1.5px solid var(--n300); border-radius: var(--r-sm);
            font-size: .88rem; font-family: 'Inter', sans-serif; background: var(--white); color: var(--n800);
            transition: border-color .15s, box-shadow .15s;
        }
        .form-control:focus, .item-input:focus {
            outline: none; border-color: var(--brand); box-shadow: 0 0 0 3px var(--brand-ring);
        }
        textarea.form-control { resize: vertical; min-height: 80px; }

        /* ── Items list ──────────────────────────────── */
        .items-section-wrap { background: transparent; }
        .items-header {
            display: grid; grid-template-columns: 80px 1fr 140px 44px; gap: 12px; align-items: center;
            padding: 10px 14px; font-size: .68rem; font-weight: 700; color: var(--n500);
            text-transform: uppercase; letter-spacing: .05em; background: var(--n50);
            border: 1px solid var(--n200); border-bottom: none; border-radius: var(--r-sm) var(--r-sm) 0 0;
        }
        #items-container { border: 1px solid var(--n200); border-top: none; border-radius: 0 0 var(--r-sm) var(--r-sm); overflow: hidden; }
        .item-row {
            display: grid; grid-template-columns: 80px 1fr 140px 44px; gap: 12px; align-items: center;
            padding: 10px 14px; background: var(--white); border-bottom: 1px solid var(--n100);
            transition: background .12s;
        }
        .item-row:hover { background: var(--n50); }
        .item-row:last-child { border-bottom: none; }
        .item-input { width: 100%; }
        .remove-item {
            width: 30px; height: 30px; border-radius: var(--r-sm); border: none;
            background: var(--danger-bg); color: var(--danger); cursor: pointer;
            display: flex; align-items: center; justify-content: center; transition: all .15s;
        }
        .remove-item:hover { background: var(--danger); color: #fff; }

        /* ── Totals card (dark gradient, matches create_order.php/edit_sale.php) ── */
        .totals-section {
            background: linear-gradient(135deg, var(--n900) 0%, var(--n800) 100%);
            border-radius: var(--r-lg); padding: 20px 24px; margin-top: 20px;
            border: 1px solid rgba(255,255,255,.05); box-shadow: 0 8px 24px rgba(15,23,42,.18);
            position: relative; overflow: hidden;
        }
        .totals-section::before {
            content: ''; position: absolute; top: -30px; right: -30px;
            width: 120px; height: 120px; border-radius: 50%;
            background: radial-gradient(circle, rgba(79,70,229,.25) 0%, transparent 70%);
            pointer-events: none;
        }
        .total-row {
            display: flex; justify-content: space-between; align-items: center;
            padding: 6px 0; font-size: .86rem; color: var(--n400); position: relative;
        }
        .total-row.grand-total {
            border-top: 1px solid rgba(255,255,255,.1); margin-top: 12px; padding-top: 14px;
            font-weight: 800; font-size: 1.3rem;
        }
        .total-row.grand-total span:first-child { color: var(--n400); font-size: .78rem; text-transform: uppercase; letter-spacing: .06em; font-weight: 700; }
        .total-amount { font-weight: 700; color: var(--white); font-variant-numeric: tabular-nums; }
        .total-row.grand-total .total-amount { font-size: 1.6rem; }

        /* ── Buttons ─────────────────────────────────── */
        .action-buttons {
            display: flex; justify-content: space-between; align-items: center;
            margin-top: 6px; padding-top: 18px; border-top: 1px solid var(--n200); flex-wrap: wrap; gap: 12px;
        }
        .btn-action {
            padding: 10px 20px; border: none; border-radius: var(--r-sm);
            font-size: .86rem; font-weight: 600; cursor: pointer; transition: all .15s;
            text-decoration: none; display: inline-flex; align-items: center; gap: 7px;
        }
        .btn-action:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,.15); text-decoration: none; }
        .btn-primary-c   { background: var(--brand); color: #fff; }
        .btn-primary-c:hover   { background: var(--brand-dark); color: #fff; }
        .btn-secondary-c { background: var(--n200); color: var(--n700); }
        .btn-secondary-c:hover { background: var(--n300); color: var(--n800); }
        .btn-success-c   { background: var(--success); color: #fff; }
        .btn-success-c:hover   { background: #047857; color: #fff; }
        .btn-add-item-c  { background: var(--brand-light); color: var(--brand); margin-left: auto; }
        .btn-add-item-c:hover { background: var(--brand); color: #fff; }

        .alert { border-radius: var(--r-sm); padding: 12px 16px; margin-bottom: 18px; display: flex; align-items: center; gap: 10px; font-size: .88rem; }
        .alert-danger  { background: var(--danger-bg); color: #991B1B; border: 1px solid var(--danger-border); }
        .alert-success { background: var(--success-bg); color: #065F46; border: 1px solid var(--success-border); }

        /* ── Preview modal (restyled to match order_details.php's stock picker) ── */
        #previewModal .modal-content { border: none; border-radius: var(--r-lg); overflow: hidden; box-shadow: 0 20px 60px rgba(0,0,0,.25); }
        #previewModal .modal-header { background: var(--n900); color: #fff; border-bottom: 3px solid var(--brand); padding: 16px 22px; }
        #previewModal .modal-title { font-size: .95rem; font-weight: 700; }
        #previewModal .btn-close { filter: invert(1) grayscale(1) brightness(2); opacity: .8; }
        #previewModal .btn-close:hover { opacity: 1; }
        .preview-modal { max-width: 800px; margin: 0; }
        .preview-content { padding: 24px; background: var(--white); }
        .preview-table { width: 100%; margin-bottom: 20px; }
        .preview-table th {
            background: var(--n50); color: var(--n500); font-size: .7rem; font-weight: 700;
            text-transform: uppercase; letter-spacing: .05em;
        }

        @media (max-width: 768px) {
            .items-header, .item-row { grid-template-columns: 1fr; gap: 8px; text-align: left; }
            .action-buttons { flex-direction: column-reverse; align-items: stretch; }
            .action-buttons > div { flex-direction: column; }
        }
    </style>

    <div class="pos-topbar">
        <div class="pos-topbar-left">
            <div class="brand-icon"><i class="fas fa-file-invoice-dollar"></i></div>
            <div class="pos-topbar-title-wrap">
                <span class="pos-topbar-title">Create Invoice</span>
                <span class="pos-topbar-sub">No. <?php echo htmlspecialchars($invoiceNumber); ?> &bull; TPIN: 30798774</span>
            </div>
        </div>
        <div class="pos-topbar-right">
            <a href="list_invoices.php?branch_id=<?php echo $branchId; ?>" class="btn-action btn-secondary-c" style="background:rgba(255,255,255,.1);color:#fff;">
                <i class="fas fa-arrow-left"></i> Back to Invoices
            </a>
        </div>
    </div>

    <div class="page-wrap">

        <div class="letterhead">
            <?php if ($companyLogoFile && file_exists($companyLogoFile)): ?>
                <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="Logo">
            <?php endif; ?>
            <div>
                <div class="letterhead-name"><?php echo htmlspecialchars($companyName); ?></div>
                <div class="letterhead-detail">
                    <?php echo htmlspecialchars($branchDetails['branch_address'] ?? ''); ?>
                    <?php if (!empty($branchDetails['branch_phone'])): ?> &bull; <?php echo htmlspecialchars($branchDetails['branch_phone']); ?><?php endif; ?>
                    <?php if (!empty($branchDetails['branch_email'])): ?> &bull; <?php echo htmlspecialchars($branchDetails['branch_email']); ?><?php endif; ?>
                    <?php if (!empty($branchDetails['branch_website'])): ?> &bull; <?php echo htmlspecialchars($branchDetails['branch_website']); ?><?php endif; ?>
                </div>
            </div>
        </div>

            <?php if (!empty($message)) echo $message; ?>

            <form method="post" action="" id="invoiceForm" class="needs-validation" novalidate>
                <div class="pos-card">
                    <div class="pos-card-title">
                        <div class="icon-badge"><i class="fas fa-user"></i></div>
                        Customer Information
                    </div>

                    <div class="form-grid">
                        <div class="form-group full-width">
                            <label for="customer_name" class="form-label">
                                <i class="fas fa-building"></i>
                                Customer/Company Name <span class="required">*</span>
                            </label>
                            <input type="text" class="form-control" id="customer_name" name="customer_name"
                                   value="<?php echo htmlspecialchars($formData['customer_name']); ?>"
                                   placeholder="Customer/Company Name" required>
                        </div>

                        <div class="form-group full-width">
                            <label for="customer_contact" class="form-label">
                                <i class="fas fa-address-book"></i>
                                Contact Details <span class="required">*</span>
                            </label>
                            <textarea class="form-control" id="customer_contact" name="customer_contact"
                                      placeholder="Address, Phone, Email" required><?php echo htmlspecialchars($formData['customer_contact']); ?></textarea>
                        </div>

                        <div class="form-group">
                            <label for="validity_days" class="form-label">
                                <i class="fas fa-calendar"></i>
                                Valid for (days) <span class="required">*</span>
                            </label>
                            <input type="number" class="form-control" id="validity_days" name="validity_days"
                                   value="<?php echo htmlspecialchars($formData['validity_days']); ?>" min="1" max="365" required>
                        </div>
                    </div>
                </div>

                <div class="pos-card">
                    <div class="pos-card-title">
                        <div class="icon-badge"><i class="fas fa-list"></i></div>
                        Invoice Items
                        <button type="button" class="btn-action btn-add-item-c" onclick="addItem()">
                            <i class="fas fa-plus"></i> Add Item
                        </button>
                    </div>

                    <div class="items-section-wrap">
                        <div class="items-header">
                            <div>Qty</div>
                            <div>Item Name</div>
                            <div>Unit Price (MWK)</div>
                            <div></div>
                        </div>

                        <div id="items-container">
                            <?php
                            $prefillItemCounter = 0;
                            foreach ($formData['items'] as $item) {
                                $prefillItemCounter++;
                                echo '<div class="item-row" id="item-' . $prefillItemCounter . '">
                                    <input type="number" class="item-input" name="item_qty_' . $prefillItemCounter . '"
                                           value="' . htmlspecialchars($item['qty'] ?? 1) . '" min="1" onchange="calculateTotal(' . $prefillItemCounter . ')" required>
                                    <input type="text" class="item-input" name="item_name_' . $prefillItemCounter . '"
                                           value="' . htmlspecialchars($item['item_name'] ?? '') . '" placeholder="Enter item name" onchange="calculateTotal(' . $prefillItemCounter . ')" required>
                                    <input type="number" class="item-input" name="unit_price_' . $prefillItemCounter . '"
                                           value="' . htmlspecialchars($item['unit_price'] ?? '') . '" step="0.01" min="0" onchange="calculateTotal(' . $prefillItemCounter . ')" required>
                                    <button type="button" class="remove-item" onclick="removeItem(' . $prefillItemCounter . ')">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>';
                            }
                            ?>
                        </div>
                    </div>
                </div>

                <div class="totals-section">
                    <div class="total-row">
                        <span>Subtotal</span>
                        <span class="total-amount" id="subtotal-display">MWK 0.00</span>
                    </div>
                    <div class="total-row">
                        <span>VAT (<?php echo htmlspecialchars(number_format($vatPercentage, 2)); ?>%)</span>
                        <span class="total-amount" id="surtax-display">MWK 0.00</span>
                    </div>
                    <div class="total-row grand-total">
                        <span>Grand Total</span>
                        <span class="total-amount" id="grand-total-display">MWK 0.00</span>
                    </div>
                </div>

                <div class="pos-card" style="margin-top:18px;">
                    <div class="pos-card-title">
                        <div class="icon-badge"><i class="fas fa-sticky-note"></i></div>
                        Additional Notes
                    </div>

                    <div class="form-group">
                        <textarea class="form-control" id="notes" name="notes" rows="3"
                                  placeholder="Any additional notes or terms..."><?php echo htmlspecialchars($formData['notes']); ?></textarea>
                    </div>
                </div>

                <input type="hidden" name="quantity" id="quantity" value="0">
                <input type="hidden" name="subtotal" id="subtotal" value="0">
                <input type="hidden" name="surtax" id="surtax" value="0">
                <input type="hidden" name="grand_total" id="grand_total" value="0">
                <input type="hidden" name="create_invoice" value="1">

                <div class="action-buttons">
                    <a href="list_invoices.php?branch_id=<?php echo $branchId; ?>" class="btn-action btn-secondary-c">
                        <i class="fas fa-times"></i>
                        Cancel
                    </a>

                    <div style="display: flex; gap: 12px;">
                        <button type="button" class="btn-action btn-primary-c" onclick="previewinvoice()">
                            <i class="fas fa-eye"></i>
                            Preview
                        </button>
                        <button type="submit" class="btn-action btn-success-c">
                            <i class="fas fa-file-alt"></i>
                            Create Invoice
                        </button>
                    </div>
                </div>
            </form>
    </div><!-- /page-wrap -->

    <div class="modal fade" id="previewModal" tabindex="-1" role="dialog" aria-labelledby="previewModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl preview-modal" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="previewModalLabel">Invoice Preview</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body preview-content">
                    <div class="text-center">
                        <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo" style="max-height: 100px; width: auto; margin-bottom: 15px;">
                        <h2>Invoice</h2>
                        <h4><?php echo htmlspecialchars($companyName); ?></h4>
                        <p><?php echo nl2br(htmlspecialchars($branchDetails['branch_address'] ?? '')); ?></p>
                        <p><?php echo htmlspecialchars($branchDetails['branch_phone'] ?? ''); ?></p>
                    </div>
                    <div class="receipt-info mt-4">
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>Invoice #:</strong> <?php echo htmlspecialchars($invoiceNumber); ?></p>
                                <p><strong>Date:</strong> <?php echo date('Y-m-d'); ?></p>
                                <p><strong>Prepared By:</strong> <?php echo htmlspecialchars($cashierName); ?></p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>Customer:</strong> <span id="preview-customer-name"></span></p>
                                <p><strong>Contact:</strong> <span id="preview-customer-contact"></span></p>
                                <p><strong>Valid Until:</strong> <span id="preview-valid-until"></span></p>
                            </div>
                        </div>
                    </div>
                    <table class="table table-bordered preview-table mt-4">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Item Name</th>
                                <th>Quantity</th>
                                <th>Unit Price (MWK)</th>
                                <th>Total (MWK)</th>
                            </tr>
                        </thead>
                        <tbody id="preview-items"></tbody>
                        <tfoot>
                            <tr>
                                <td colspan="4" class="text-end"><strong>Subtotal:</strong></td>
                                <td id="preview-subtotal">MWK 0.00</td>
                            </tr>
                            <tr>
                                <td colspan="4" class="text-end"><strong>VAT (<?php echo htmlspecialchars(number_format($vatPercentage, 2)); ?>%):</strong></td>
                                <td id="preview-surtax">MWK 0.00</td>
                            </tr>
                            <tr>
                                <td colspan="4" class="text-end"><strong>Grand Total:</strong></td>
                                <td id="preview-grand-total">MWK 0.00</td>
                            </tr>
                        </tfoot>
                    </table>
                    <div class="receipt-notes">
                        <h5>Notes:</h5>
                        <p id="preview-notes">No additional notes provided.</p>
                    </div>
                    <div class="receipt-validity mt-3">
                        <p>This invoice is valid until <span id="preview-valid-until-footer"></span>.</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const vatRate = <?php echo json_encode($vatRate); ?>;
let itemCounter = <?php echo $prefillItemCounter; ?>;

        function addItem() {
            itemCounter++;
            const container = document.getElementById('items-container');
            const itemRow = document.createElement('div');
            itemRow.className = 'item-row';
            itemRow.id = `item-${itemCounter}`;

            itemRow.innerHTML = `
                <input type="number" class="item-input" name="item_qty_${itemCounter}"
                       placeholder="Enter quantity" min="1" onchange="calculateTotal(${itemCounter})" required>
                <input type="text" class="item-input" name="item_name_${itemCounter}"
                       placeholder="Enter item name" onchange="calculateTotal(${itemCounter})" required>
                <input type="number" class="item-input" name="unit_price_${itemCounter}"
                       placeholder="0.00" step="0.01" min="0" onchange="calculateTotal(${itemCounter})" required>
                <button type="button" class="remove-item" onclick="removeItem(${itemCounter})">
                    <i class="fas fa-times"></i>
                </button>
            `;

            container.appendChild(itemRow);
            updateQuantity();
            calculateGrandTotal();
        }

        function removeItem(id) {
            const item = document.getElementById(`item-${id}`);
            if (item) {
                item.remove();
                updateQuantity();
                calculateGrandTotal();
            }
        }

        function calculateTotal(id) {
            const qtyInput = document.querySelector(`input[name="item_qty_${id}"]`);
            const qty = parseInt(qtyInput.value, 10) || 0;
            if (qty < 1) {
                qtyInput.value = 1;
            }
            calculateGrandTotal();
        }

        function calculateGrandTotal() {
            let subtotal = 0;
            document.querySelectorAll('.item-row').forEach(row => {
                const qty = parseInt(row.querySelector(`input[name^="item_qty_"]`).value, 10) || 0;
                const unitPrice = parseFloat(row.querySelector(`input[name^="unit_price_"]`).value) || 0;
                subtotal += qty * unitPrice;
            });

            let surtax = subtotal * vatRate;
            let grandTotal = subtotal + surtax;
            if (!Number.isFinite(subtotal)) subtotal = 0;
            if (!Number.isFinite(surtax)) surtax = 0;
            if (!Number.isFinite(grandTotal)) grandTotal = 0;

            document.getElementById('subtotal-display').textContent = `MWK ${subtotal.toFixed(2)}`;
            document.getElementById('surtax-display').textContent = `MWK ${surtax.toFixed(2)}`;
            document.getElementById('grand-total-display').textContent = `MWK ${grandTotal.toFixed(2)}`;

            document.getElementById('subtotal').value = subtotal.toFixed(2);
            document.getElementById('surtax').value = surtax.toFixed(2);
            document.getElementById('grand_total').value = grandTotal.toFixed(2);
        }

        function updateQuantity() {
            const itemRows = document.querySelectorAll('.item-row').length;
            document.getElementById('quantity').value = itemRows;
        }

        function previewinvoice() {
            const customerName = document.getElementById('customer_name').value || 'Not provided';
            const customerContact = document.getElementById('customer_contact').value || 'Not provided';
            const validityDays = parseInt(document.getElementById('validity_days').value) || 30;
            const notes = document.getElementById('notes').value || 'No additional notes provided.';

            if (!customerName || !customerContact || document.querySelectorAll('.item-row').length === 0) {
                alert('Please fill in customer information and add at least one item.');
                return;
            }


            let hasDefaultQty = false;
            document.querySelectorAll('.item-row').forEach(row => {
                const qty = parseInt(row.querySelector(`input[name^="item_qty_"]`).value, 10) || 0;
                if (qty === 1) {
                    hasDefaultQty = true;
                }
            });
            if (hasDefaultQty) {
                if (!confirm('Some items have a quantity of 1. Are you sure these quantities are correct?')) {
                    return;
                }
            }

            const validUntil = new Date();
            validUntil.setDate(validUntil.getDate() + validityDays);
            const formattedValidUntil = validUntil.toISOString().split('T')[0];

            document.getElementById('preview-customer-name').textContent = customerName;
            document.getElementById('preview-customer-contact').textContent = customerContact;
            document.getElementById('preview-valid-until').textContent = formattedValidUntil;
            document.getElementById('preview-valid-until-footer').textContent = formattedValidUntil;
            document.getElementById('preview-notes').textContent = notes;

            const itemsContainer = document.getElementById('preview-items');
            itemsContainer.innerHTML = '';
            let subtotal = 0;

            document.querySelectorAll('.item-row').forEach((row, index) => {
                const qtyInput = row.querySelector(`input[name^="item_qty_"]`);
                const qty = parseInt(qtyInput.value, 10) || 0;
                if (qty < 1) {
                    qtyInput.value = 1;
                }
                const itemName = row.querySelector(`input[name^="item_name_"]`).value || 'Unknown Item';
                const unitPrice = parseFloat(row.querySelector(`input[name^="unit_price_"]`).value) || 0;
                const total = qty * unitPrice;
                subtotal += total;

                itemsContainer.innerHTML += `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${itemName}</td>
                        <td>${qty}</td>
                        <td>MWK ${unitPrice.toFixed(2)}</td>
                        <td>MWK ${total.toFixed(2)}</td>
                    </tr>
                `;
            });

            const surtax = subtotal * vatRate;
            const grandTotal = subtotal + surtax;

            document.getElementById('preview-subtotal').textContent = `MWK ${subtotal.toFixed(2)}`;
            document.getElementById('preview-surtax').textContent = `MWK ${surtax.toFixed(2)}`;
            document.getElementById('preview-grand-total').textContent = `MWK ${grandTotal.toFixed(2)}`;

            bootstrap.Modal.getOrCreateInstance(document.getElementById('previewModal')).show();
        }

        document.addEventListener('DOMContentLoaded', function() {
            if (document.querySelectorAll('.item-row').length === 0) {
                addItem();
            } else {
                calculateGrandTotal();
            }

            const form = document.getElementById('invoiceForm');
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }

                let hasDefaultQty = false;
                document.querySelectorAll('input[name^="item_qty_"]').forEach(input => {
                    const qty = parseInt(input.value, 10) || 0;
                    if (qty < 1) {
                        input.value = 1;
                    }
                    if (qty === 1) {
                        hasDefaultQty = true;
                    }
                });
                if (hasDefaultQty) {
                    if (!confirm('Some items have a quantity of 1. Are you sure these quantities are correct?')) {
                        event.preventDefault();
                        event.stopPropagation();
                        return;
                    }
                }
                calculateGrandTotal();
                form.classList.add('was-validated');
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
