<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName = Branding::companyName();
$companyLogo = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
$settings = Branding::settings();
$vatPercentage = (float)$settings['vat_percentage'];
$vatRate = $vatPercentage / 100;
$profitPercentage = (float)$settings['profit_percentage'];
$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/Quotation.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']);

$quotation = new Quotation($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) ?: [];
$companyDetails = Branding::documentDetailsForBranch($branchDetails);
$companyContactLine = Branding::contactLine($companyDetails);
$cashierName = $auth->getUserName($_SESSION['user_id']);
$quotationNumber = 'QT' . 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_quotation'])) {
    $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 {
            $quotationNumber = 'QT' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            $result = $quotation->createQuotation(
                $branchId,
                $_SESSION['user_id'],
                $quotationNumber,
                $customerName,
                $customerContact,
                $items,
                $calculatedSubtotal,
                $calculatedSurtax,
                $calculatedTotal,
                $validityDays,
                $notes
            );
            $retryCount++;
        } while (!$result['success'] && strpos($result['message'], 'Duplicate entry') !== false && $retryCount < $maxRetries);

        if ($result['success']) {
            $_SESSION['quotation_data'] = [
                'quotation_id' => $result['quotation_id'],
                'quotation_number' => $quotationNumber,
                '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: quotation_receipt.php');
            exit();
        } else {
            $failureReason = 'Failed to create quotation: ' . $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 {
            $draftQuotationNumber = 'QT' . date('Y') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            $draftResult = $quotation->saveDraft(
                $branchId,
                $_SESSION['user_id'],
                $draftQuotationNumber,
                $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_quotation.php?quotation_id=' . $draftResult['quotation_id'] . '&draft=1&error=' . urlencode($failureReason . ' Your quotation 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>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #eef1f5;
            min-height: 100vh;
            padding: 32px 20px;
            color: #1f2937;
        }

        .container {
            max-width: 950px;
            margin: 0 auto;
            background: #ffffff;
            border-radius: 6px;
            border: 1px solid #e2e8f0;
            box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06), 0 8px 24px rgba(15, 23, 42, 0.05);
            overflow: hidden;
        }

        .quotation-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 24px;
            padding: 32px 40px;
            border-bottom: 3px solid #0f172a;
        }

        .company-logo {
            max-height: 64px;
            width: auto;
            margin-bottom: 12px;
        }

        .company-name {
            font-size: 22px;
            font-weight: 700;
            color: #0f172a;
            margin-bottom: 8px;
            letter-spacing: 0.5px;
        }

        .company-tagline {
            font-size: 13px;
            margin-bottom: 10px;
            color: #64748b;
            line-height: 1.6;
        }

        .company-details {
            font-size: 12.5px;
            line-height: 1.7;
            color: #64748b;
        }

        .quotation-meta {
            text-align: right;
            flex-shrink: 0;
            min-width: 220px;
        }

        .quotation-title {
            font-size: 26px;
            font-weight: 700;
            color: #0f172a;
            letter-spacing: 3px;
            margin-bottom: 14px;
        }

        .quotation-number,
        .tpin-number {
            font-size: 13px;
            color: #475569;
            padding: 4px 0;
        }

        .quotation-number strong,
        .tpin-number strong {
            color: #0f172a;
            font-weight: 600;
        }

        .form-container {
            padding: 36px 40px;
        }

        .form-section {
            margin-bottom: 24px;
            background: #ffffff;
            padding: 22px 24px;
            border-radius: 6px;
            border: 1px solid #e2e8f0;
        }

        .section-title {
            font-size: 13px;
            font-weight: 700;
            color: #0f172a;
            text-transform: uppercase;
            letter-spacing: 0.6px;
            margin-bottom: 18px;
            padding-bottom: 12px;
            border-bottom: 1px solid #eef1f5;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-icon {
            width: 22px;
            height: 22px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #2563eb;
            font-size: 13px;
        }

        .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-weight: 600;
            font-size: 13px;
            color: #334155;
            margin-bottom: 6px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .form-label i {
            color: #94a3b8;
            font-size: 12px;
        }

        .required {
            color: #dc2626;
        }

        .form-control, .item-input {
            padding: 10px 14px;
            border: 1px solid #cbd5e1;
            border-radius: 5px;
            font-size: 14px;
            transition: border-color 0.15s ease, box-shadow 0.15s ease;
            background: white;
            color: #1f2937;
        }

        .form-control:focus, .item-input:focus {
            outline: none;
            border-color: #2563eb;
            box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12);
        }

        textarea.form-control {
            resize: vertical;
            min-height: 72px;
        }

        .items-section {
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            overflow: hidden;
        }

        .items-header {
            background: #f8fafc;
            color: #475569;
            padding: 12px 20px;
            font-weight: 700;
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.4px;
            display: grid;
            grid-template-columns: 80px 1fr 160px 48px;
            gap: 15px;
            align-items: center;
            border-bottom: 1px solid #e2e8f0;
        }

        .item-row {
            padding: 12px 20px;
            border-bottom: 1px solid #eef1f5;
            display: grid;
            grid-template-columns: 80px 1fr 160px 48px;
            gap: 15px;
            align-items: center;
            background: white;
            transition: background 0.15s ease;
        }

        .item-row:hover {
            background: #f8fafc;
        }

        .item-row:last-child {
            border-bottom: none;
        }

        .item-input {
            padding: 8px 10px;
            border: 1px solid #cbd5e1;
            border-radius: 4px;
            font-size: 13px;
            width: 100%;
        }

        .item-input:focus {
            outline: none;
            border-color: #2563eb;
            box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.12);
        }

        .remove-item {
            background: #ffffff;
            color: #dc2626;
            border: 1px solid #e2e8f0;
            border-radius: 5px;
            width: 30px;
            height: 30px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.15s ease;
        }

        .remove-item:hover {
            background: #fef2f2;
            border-color: #fecaca;
        }

        .totals-section {
            background: #f8fafc;
            padding: 20px 24px;
            border-radius: 6px;
            margin-top: 18px;
            border: 1px solid #e2e8f0;
            max-width: 360px;
            margin-left: auto;
        }

        .total-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 8px 0;
            font-size: 14px;
            color: #475569;
        }

        .total-row.grand-total {
            border-top: 1px solid #cbd5e1;
            margin-top: 8px;
            padding-top: 12px;
            font-weight: 700;
            font-size: 17px;
            color: #0f172a;
        }

        .total-amount {
            font-weight: 600;
            color: #0f172a;
            font-variant-numeric: tabular-nums;
        }

        .action-buttons {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 28px;
            padding-top: 20px;
            border-top: 1px solid #e2e8f0;
        }

        .btn {
            padding: 10px 22px;
            border: 1px solid transparent;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: background 0.15s ease, border-color 0.15s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: #ffffff;
            color: #2563eb;
            border-color: #93c5fd;
        }

        .btn-primary:hover {
            background: #eff6ff;
        }

        .btn-secondary {
            background: #ffffff;
            color: #475569;
            border-color: #cbd5e1;
        }

        .btn-secondary:hover {
            background: #f8fafc;
        }

        .btn-success {
            background: #0f172a;
            color: white;
        }

        .btn-success:hover {
            background: #1e293b;
        }

        .alert {
            padding: 13px 18px;
            border-radius: 5px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 14px;
        }

        .alert-danger {
            background: #fef2f2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }

        .alert-success {
            background: #f0fdf4;
            color: #166534;
            border: 1px solid #bbf7d0;
        }

        @media (max-width: 768px) {
            .container {
                margin: 0;
                border-radius: 6px;
            }

            .quotation-header {
                flex-direction: column;
                padding: 24px;
            }

            .quotation-meta {
                text-align: left;
            }

            .form-container {
                padding: 20px;
            }

            .items-header,
            .item-row {
                grid-template-columns: 1fr;
                gap: 10px;
                text-align: left;
            }

            .totals-section {
                max-width: none;
            }

            .action-buttons {
                flex-direction: column;
                gap: 15px;
            }
        }

        .preview-modal {
            max-width: 800px;
            margin: 30px auto;
        }

        .preview-content {
            padding: 0;
            background: #eef1f5;
        }

        .preview-doc {
            background: #ffffff;
            margin: 24px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            overflow: hidden;
        }

        .preview-doc-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 20px;
            padding: 28px 32px;
            border-bottom: 3px solid #0f172a;
        }

        .preview-doc-logo {
            max-height: 56px;
            width: auto;
            margin-bottom: 10px;
        }

        .preview-doc-name {
            font-size: 19px;
            font-weight: 700;
            color: #0f172a;
            margin-bottom: 6px;
        }

        .preview-doc-tagline,
        .preview-doc-address {
            font-size: 12.5px;
            color: #64748b;
            line-height: 1.6;
        }

        .preview-doc-meta {
            text-align: right;
            flex-shrink: 0;
            min-width: 200px;
        }

        .preview-doc-title {
            font-size: 22px;
            font-weight: 700;
            color: #0f172a;
            letter-spacing: 2.5px;
            margin-bottom: 10px;
        }

        .preview-doc-meta-row {
            font-size: 12.5px;
            color: #475569;
            padding: 2px 0;
        }

        .preview-doc-meta-row strong {
            color: #0f172a;
            font-weight: 600;
        }

        .preview-doc-parties {
            display: flex;
            justify-content: space-between;
            gap: 20px;
            padding: 20px 32px;
            background: #f8fafc;
            border-bottom: 1px solid #e2e8f0;
        }

        .preview-doc-parties > div:last-child {
            text-align: right;
        }

        .preview-doc-label {
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #94a3b8;
            margin-bottom: 6px;
        }

        .preview-doc-value {
            font-size: 14.5px;
            font-weight: 600;
            color: #0f172a;
        }

        .preview-doc-value-sub {
            font-size: 13px;
            color: #64748b;
            margin-top: 2px;
            white-space: pre-line;
        }

        .preview-doc-body {
            padding: 24px 32px 32px;
        }

        .preview-table {
            width: 100%;
            margin-bottom: 0;
            border-collapse: collapse;
        }

        .preview-table th {
            background-color: #f8fafc;
            color: #475569;
            font-size: 11.5px;
            text-transform: uppercase;
            letter-spacing: 0.4px;
            font-weight: 700;
            padding: 10px 12px;
            border-bottom: 1px solid #e2e8f0;
            border-top: none;
        }

        .preview-table td {
            padding: 10px 12px;
            font-size: 13.5px;
            color: #1f2937;
            border-bottom: 1px solid #eef1f5;
            border-top: none;
        }

        .preview-table tfoot td {
            border-bottom: none;
            padding-top: 8px;
            padding-bottom: 8px;
            color: #475569;
        }

        .preview-table tfoot tr:last-child td {
            border-top: 1px solid #cbd5e1;
            padding-top: 12px;
            font-weight: 700;
            font-size: 15px;
            color: #0f172a;
        }

        .preview-doc-notes {
            margin-top: 22px;
            padding-top: 18px;
            border-top: 1px solid #eef1f5;
        }

        .preview-doc-notes p {
            font-size: 13.5px;
            color: #475569;
            margin-top: 4px;
        }

        .preview-doc-footer {
            margin-top: 14px;
            font-size: 12.5px;
            color: #94a3b8;
        }
    </style>
    <div class="container">
        <div class="quotation-header">
            <div class="company-info">
                <?php if (!empty($companyLogo)): ?>
                    <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo" class="company-logo">
                <?php endif; ?>
                <div class="company-name"><?php echo htmlspecialchars($companyName); ?></div>
                <div class="company-tagline"><?php echo nl2br(htmlspecialchars($companyDetails['tagline'])); ?></div>
                <div class="company-details">
                    <?php echo nl2br(htmlspecialchars($companyDetails['address'])); ?><br>
                    <?php echo htmlspecialchars($companyContactLine); ?>
                </div>
            </div>

            <div class="quotation-meta">
                <div class="quotation-title">QUOTATION</div>
                <div class="quotation-number"><strong>No.</strong> <?php echo htmlspecialchars($quotationNumber); ?></div>
                <div class="quotation-number"><strong>Date:</strong> <?php echo date('Y-m-d'); ?></div>
                <div class="tpin-number"><strong>TPIN:</strong> 30798774</div>
            </div>
        </div>

        <div class="form-container">
            <?php if (!empty($message)) echo $message; ?>

            <form method="post" action="" id="quotationForm" class="needs-validation" novalidate>
                <div class="form-section">
                    <div class="section-title">
                        <div class="section-icon">
                            <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="form-section">
                    <div class="section-title">
                        <div class="section-icon">
                            <i class="fas fa-list"></i>
                        </div>
                        Quotation Items
                        <button type="button" class="btn btn-success" onclick="addItem()" style="margin-left: auto;">
                            <i class="fas fa-plus"></i> Add Item
                        </button>
                    </div>

                    <div class="items-section">
                        <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="form-section">
                    <div class="section-title">
                        <div class="section-icon">
                            <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_quotation" value="1">

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

                    <div style="display: flex; gap: 15px;">
                        <button type="button" class="btn btn-primary" onclick="previewQuotation()">
                            <i class="fas fa-eye"></i>
                            Preview
                        </button>
                        <button type="submit" class="btn btn-success">
                            <i class="fas fa-file-alt"></i>
                            Create Quotation
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>


    <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">Quotation 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="preview-doc">
                        <div class="preview-doc-header">
                            <div class="preview-doc-company">
                                <?php if (!empty($companyLogo)): ?>
                                    <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo" class="preview-doc-logo">
                                <?php endif; ?>
                                <div class="preview-doc-name"><?php echo htmlspecialchars($companyName); ?></div>
                                <div class="preview-doc-tagline"><?php echo nl2br(htmlspecialchars($companyDetails['tagline'])); ?></div>
                                <div class="preview-doc-address">
                                    <?php echo nl2br(htmlspecialchars($companyDetails['address'])); ?><br>
                                    <?php echo htmlspecialchars($companyContactLine); ?>
                                </div>
                            </div>
                            <div class="preview-doc-meta">
                                <div class="preview-doc-title">QUOTATION</div>
                                <div class="preview-doc-meta-row"><strong>No.</strong> <?php echo htmlspecialchars($quotationNumber); ?></div>
                                <div class="preview-doc-meta-row"><strong>Date:</strong> <?php echo date('Y-m-d'); ?></div>
                                <div class="preview-doc-meta-row"><strong>Prepared by:</strong> <?php echo htmlspecialchars($cashierName); ?></div>
                            </div>
                        </div>

                        <div class="preview-doc-parties">
                            <div>
                                <div class="preview-doc-label">Quotation For</div>
                                <div class="preview-doc-value" id="preview-customer-name"></div>
                                <div class="preview-doc-value-sub" id="preview-customer-contact"></div>
                            </div>
                            <div>
                                <div class="preview-doc-label">Valid Until</div>
                                <div class="preview-doc-value" id="preview-valid-until"></div>
                            </div>
                        </div>

                        <div class="preview-doc-body">
                            <table class="preview-table">
                                <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">Subtotal:</td>
                                        <td id="preview-subtotal">MWK 0.00</td>
                                    </tr>
                                    <tr>
                                        <td colspan="4" class="text-end">VAT (<?php echo htmlspecialchars(number_format($vatPercentage, 2)); ?>%):</td>
                                        <td id="preview-surtax">MWK 0.00</td>
                                    </tr>
                                    <tr>
                                        <td colspan="4" class="text-end">Grand Total:</td>
                                        <td id="preview-grand-total">MWK 0.00</td>
                                    </tr>
                                </tfoot>
                            </table>

                            <div class="preview-doc-notes">
                                <div class="preview-doc-label">Notes</div>
                                <p id="preview-notes">No additional notes provided.</p>
                            </div>

                            <div class="preview-doc-footer">
                                <p>This quotation is valid until <span id="preview-valid-until-footer"></span>.</p>
                            </div>
                        </div>
                    </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 previewQuotation() {
            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('quotationForm');
            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'; ?>
