<?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/Quotation.php';
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../classes/Branch.php';

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


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

$auth = new Auth($conn);
$quotation = new Quotation($conn, $logger);
$branch = new Branch($conn);

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

$quotationId = isset($_GET['quotation_id']) ? (int)$_GET['quotation_id'] : 0;
$quotationData = $quotation->getQuotationById($quotationId) ?? [];
if (!$quotationData || ($auth->getUserBranch($_SESSION['user_id']) != ($quotationData['branch_id'] ?? null) && !$auth->isSuperAdmin($_SESSION['user_id']))) {
    header('Location: list_quotations.php?error=' . urlencode('Quotation not found or access denied.'));
    exit();
}

$branchDetails = $branch->getBranchById((int)($quotationData['branch_id'] ?? 0)) ?: [];
$companyDetails = Branding::documentDetailsForBranch($branchDetails);
$companyContactLine = Branding::contactLine($companyDetails);

$creatorId = $quotationData['created_by'] ?? null;
$creatorName = 'Unknown';
if ($creatorId) {
    $creatorName = $auth->getUserName($creatorId) ?? 'Unknown';
    if ($creatorName === 'Unknown') {
        error_log("Failed to retrieve username for user_id: $creatorId in quotation ID: $quotationId");
    }
} else {
    error_log("No created_by field found for quotation ID: $quotationId");
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customerName = trim($_POST['customer_name'] ?? $quotationData['customer_name'] ?? '');
    $customerContact = trim($_POST['customer_contact'] ?? $quotationData['customer_contact'] ?? '');
    $validUntil = $_POST['valid_until'] ?? $quotationData['valid_until'] ?? date('Y-m-d', strtotime('+30 days'));
    $status = $_POST['status'] ?? $quotationData['status'] ?? 'pending';
    $notes = trim($_POST['notes'] ?? $quotationData['notes'] ?? '');


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


    $subtotal = 0;
    foreach ($items as $item) {
        $subtotal += $item['qty'] * $item['unit_price'];
    }
    $subtotal = round($subtotal, 2);
    $surtax = round($subtotal * $vatRate, 2);
    $grandTotal = round($subtotal + $surtax, 2);


    try {
        $result = $quotation->updateQuotation($quotationId, $customerName, $customerContact, $validUntil, $status, $items, $subtotal, $surtax, $grandTotal, $notes);
        if ($result) {
            header('Location: list_quotations.php?success=' . urlencode('Quotation updated successfully.') . '&branch_id=' . $quotationData['branch_id']);
            exit();
        } else {
            header('Location: edit_quotation.php?quotation_id=' . $quotationId . '&error=' . urlencode('Failed to update quotation.'));
            exit();
        }
    } catch (Exception $e) {
        error_log("Error updating quotation: " . $e->getMessage());
        header('Location: edit_quotation.php?quotation_id=' . $quotationId . '&error=' . urlencode('Database error: ' . $e->getMessage()));
        exit();
    }
}
?>

<?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: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .quotation-header {
            background: linear-gradient(45deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
            position: relative;
        }

        .company-logo {
            max-height: 100px;
            width: auto;
            margin-bottom: 15px;
        }

        .company-name {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 2px;
        }

        .company-tagline {
            font-size: 14px;
            margin-bottom: 20px;
            opacity: 0.9;
            line-height: 1.6;
        }

        .company-details {
            font-size: 12px;
            line-height: 1.8;
            opacity: 0.8;
        }

        .quotation-title {
            position: absolute;
            top: 30px;
            right: 30px;
            background: #e74c3c;
            padding: 10px 20px;
            border-radius: 25px;
            font-weight: bold;
            font-size: 18px;
        }

        .quotation-number {
            position: absolute;
            top: 80px;
            right: 30px;
            background: rgba(255, 255, 255, 0.2);
            padding: 8px 16px;
            border-radius: 20px;
            font-size: 14px;
        }

        .tpin-number {
            position: absolute;
            top: 120px;
            right: 30px;
            font-size: 12px;
            opacity: 0.8;
        }

        .form-container {
            padding: 40px;
        }

        .form-section {
            margin-bottom: 30px;
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            border-left: 4px solid #3498db;
        }

        .section-title {
            font-size: 18px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .section-icon {
            width: 30px;
            height: 30px;
            background: linear-gradient(45deg, #3498db, #2980b9);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 14px;
        }

        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group.full-width {
            grid-column: 1 / -1;
        }

        .form-label {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .required {
            color: #e74c3c;
        }

        .form-control, .item-input {
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: white;
        }

        .form-control:focus, .item-input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
            transform: translateY(-1px);
        }

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

        .items-section {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            overflow: hidden;
        }

        .items-header {
            background: linear-gradient(45deg, #34495e, #2c3e50);
            color: white;
            padding: 15px 20px;
            font-weight: 600;
            display: grid;
            grid-template-columns: 80px 1fr 120px 60px;
            gap: 15px;
            align-items: center;
        }

        .item-row {
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            display: grid;
            grid-template-columns: 80px 1fr 120px 60px;
            gap: 15px;
            align-items: center;
            background: white;
            transition: all 0.2s ease;
        }

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

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

        .item-input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 13px;
            width: 100%;
        }

        .item-input:focus {
            outline: none;
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.1);
        }

        .remove-item {
            background: #e74c3c;
            color: white;
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
        }

        .remove-item:hover {
            background: #c0392b;
            transform: scale(1.1);
        }

        .totals-section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            margin-top: 20px;
            border: 2px solid #e9ecef;
        }

        .total-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            font-size: 16px;
        }

        .total-row.grand-total {
            border-top: 2px solid #2c3e50;
            margin-top: 15px;
            padding-top: 15px;
            font-weight: bold;
            font-size: 20px;
            color: #2c3e50;
        }

        .total-amount {
            font-weight: 600;
            color: #27ae60;
        }

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

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn-primary {
            background: linear-gradient(45deg, #3498db, #2980b9);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(52, 152, 219, 0.3);
        }

        .btn-secondary {
            background: #95a5a6;
            color: white;
        }

        .btn-secondary:hover {
            background: #7f8c8d;
            transform: translateY(-2px);
        }

        .btn-success {
            background: linear-gradient(45deg, #27ae60, #229954);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(39, 174, 96, 0.3);
        }

        .alert {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

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

            .quotation-header {
                padding: 20px;
            }

            .quotation-title,
            .quotation-number,
            .tpin-number {
                position: static;
                margin: 10px 0;
                display: inline-block;
            }

            .form-container {
                padding: 20px;
            }

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

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

        .container {
            animation: slideUp 0.6s ease-out;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

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

        .preview-content {
            padding: 20px;
            background: white;
            border-radius: 10px;
        }

        .preview-table {
            width: 100%;
            margin-bottom: 20px;
        }

        .preview-table th {
            background-color: #f5f5f5;
        }
    </style>
    <div class="container">
        <div class="quotation-header">
            <div class="quotation-title">QUOTATION</div>
            <div class="quotation-number">No. <?php echo htmlspecialchars($quotationData['quotation_number'] ?? 'N/A'); ?></div>
            <div class="tpin-number">TPIN: 30798774</div>

            <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="form-container">
            <?php if (($quotationData['status'] ?? '') === 'draft' && !isset($_GET['error'])): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    This quotation was saved as a draft after an error during creation. Please review the details below, complete any missing information, and click Update to finalize it.
                </div>
            <?php endif; ?>

            <?php if (isset($_GET['error'])): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars(urldecode($_GET['error'])); ?>
                </div>
            <?php endif; ?>

            <form method="POST" action="" id="quotationForm" class="needs-validation" novalidate>
                <input type="hidden" id="quantity" name="quantity" value="<?php echo count($quotationData['items'] ?? []); ?>">

                <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($quotationData['customer_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($quotationData['customer_contact'] ?? ''); ?></textarea>
                        </div>

                        <div class="form-group">
                            <label for="valid_until" class="form-label">
                                <i class="fas fa-calendar"></i>
                                Valid Until: <span class="required">*</span>
                            </label>
                            <input type="date" class="form-control" id="valid_until" name="valid_until"
                                   value="<?php echo htmlspecialchars($quotationData['valid_until'] ?? date('Y-m-d', strtotime('+30 days'))); ?>" required>
                        </div>

                        <div class="form-group">
                            <label for="status" class="form-label">
                                <i class="fas fa-check-circle"></i>
                                Status: <span class="required">*</span>
                            </label>
                            <select class="form-control" id="status" name="status" required>
                                <option value="draft" <?php echo ($quotationData['status'] ?? 'pending') === 'draft' ? 'selected' : ''; ?>>Draft</option>
                                <option value="pending" <?php echo ($quotationData['status'] ?? 'pending') === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="approved" <?php echo ($quotationData['status'] ?? 'pending') === 'approved' ? 'selected' : ''; ?>>Approved</option>
                            </select>
                        </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
                            $items = $quotationData['items'] ?? [];
                            $itemCounter = 0;
                            foreach ($items as $item) {
                                $itemCounter++;
                                $quantity = isset($item['quantity']) ? (int)$item['quantity'] : 1;
                                echo '<div class="item-row" id="item-' . $itemCounter . '">
                                    <input type="number" class="item-input" name="item_qty_' . $itemCounter . '"
                                           value="' . htmlspecialchars($quantity) . '" min="1" onchange="calculateTotal(' . $itemCounter . ')" required>
                                    <input type="text" class="item-input" name="item_name_' . $itemCounter . '"
                                           value="' . htmlspecialchars($item['item_name'] ?? '') . '" onchange="calculateTotal(' . $itemCounter . ')" required>
                                    <input type="number" class="item-input" name="unit_price_' . $itemCounter . '"
                                           value="' . htmlspecialchars($item['unit_price'] ?? 0) . '" 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>
                                </div>';
                            }
                            if (empty($items)) {
                                echo '<div class="item-row" id="item-1">
                                    <input type="number" class="item-input" name="item_qty_1" value="1" min="1" onchange="calculateTotal(1)" required>
                                    <input type="text" class="item-input" name="item_name_1" value="" onchange="calculateTotal(1)" required>
                                    <input type="number" class="item-input" name="unit_price_1" value="0" step="0.01" min="0" onchange="calculateTotal(1)" required>
                                    <button type="button" class="remove-item" onclick="removeItem(1)">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>';
                                $itemCounter = 1;
                            }
                            ?>
                        </div>
                    </div>
                </div>

                <div class="totals-section">
                    <div class="total-row">
                        <span>Subtotal:</span>
                        <span class="total-amount" id="subtotal-display">MWK <?php echo number_format($quotationData['subtotal'] ?? 0, 2); ?></span>
                    </div>
                    <div class="total-row">
                        <span>VAT (<?php echo htmlspecialchars(number_format($vatPercentage, 2)); ?>%):</span>
                        <span class="total-amount" id="surtax-display">MWK <?php echo number_format($quotationData['surtax'] ?? 0, 2); ?></span>
                    </div>
                    <div class="total-row grand-total">
                        <span>Grand Total:</span>
                        <span class="total-amount" id="grand-total-display">MWK <?php echo number_format($quotationData['total_amount'] ?? 0, 2); ?></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($quotationData['notes'] ?? ''); ?></textarea>
                    </div>
                </div>

                <div class="action-buttons">
                    <a href="list_quotations.php?branch_id=<?php echo $quotationData['branch_id']; ?>" 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-save"></i>
                            Update 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="text-center">
                        <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="<?php echo htmlspecialchars($companyName); ?> Logo" class="company-logo">
                        <h2>QUOTATION</h2>
                        <h4><?php echo htmlspecialchars($companyName); ?></h4>
                        <p><?php echo nl2br(htmlspecialchars($companyDetails['address'])); ?></p>
                        <p><?php echo htmlspecialchars($companyContactLine); ?></p>
                        <p><?php echo nl2br(htmlspecialchars($companyDetails['tagline'])); ?></p>
                    </div>
                    <div class="receipt-info mt-4">
                        <div class="row">
                            <div class="col-md-6">
                                <p><strong>Quotation #:</strong> <?php echo htmlspecialchars($quotationData['quotation_number'] ?? 'N/A'); ?></p>
                                <p><strong>Date:</strong> <?php echo (new DateTime($quotationData['created_at'] ?? 'now'))->format('Y-m-d'); ?></p>
                                <p><strong>Prepared By:</strong> <?php echo htmlspecialchars($creatorName); ?></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>
                                <p><strong>Status:</strong> <span id="preview-status"></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"></td>
                            </tr>
                            <tr>
                                <td colspan="4" class="text-end"><strong>VAT (<?php echo htmlspecialchars(number_format($vatPercentage, 2)); ?>%):</strong></td>
                                <td id="preview-surtax"></td>
                            </tr>
                            <tr>
                                <td colspan="4" class="text-end"><strong>Grand Total:</strong></td>
                                <td id="preview-grand-total"></td>
                            </tr>
                        </tfoot>
                    </table>
                    <div class="receipt-notes">
                        <h5>Notes:</h5>
                        <p id="preview-notes"><?php echo htmlspecialchars($quotationData['notes'] ?? 'No additional notes provided.'); ?></p>
                    </div>
                    <div class="receipt-validity mt-3">
                        <p>This quotation is valid until <span id="preview-valid-until-footer"><?php echo htmlspecialchars($quotationData['valid_until'] ?? 'N/A'); ?></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 $itemCounter; ?>;

        function addItem() {
            itemCounter++;
            const itemsContainer = document.getElementById('items-container');
            const newItem = document.createElement('div');
            newItem.className = 'item-row';
            newItem.id = `item-${itemCounter}`;
            newItem.innerHTML = `
                <input type="number" class="item-input" name="item_qty_${itemCounter}" value="1" min="1" onchange="calculateTotal(${itemCounter})" required>
                <input type="text" class="item-input" name="item_name_${itemCounter}" value="" onchange="calculateTotal(${itemCounter})" required>
                <input type="number" class="item-input" name="unit_price_${itemCounter}" value="0" 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>
            `;
            itemsContainer.appendChild(newItem);
            document.getElementById('quantity').value = itemCounter;
            calculateTotal(itemCounter);
        }

        function removeItem(index) {
            const itemRow = document.getElementById(`item-${index}`);
            if (itemRow) {
                itemRow.remove();
                calculateTotal();
            }
        }

        function calculateTotal(index = null) {
            let subtotal = 0;
            const items = document.querySelectorAll('.item-row');
            items.forEach((item, i) => {
                const qty = parseInt(item.querySelector(`input[name="item_qty_${i + 1}"]`)?.value || 0);
                const unitPrice = parseFloat(item.querySelector(`input[name="unit_price_${i + 1}"]`)?.value || 0);
                subtotal += qty * unitPrice;
            });
            const surtax = subtotal * vatRate;
            const grandTotal = subtotal + surtax;

            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)}`;
        }

        function previewQuotation() {
            const customerName = document.getElementById('customer_name').value || '<?php echo htmlspecialchars($quotationData['customer_name'] ?? 'Not provided'); ?>';
            const customerContact = document.getElementById('customer_contact').value || '<?php echo htmlspecialchars($quotationData['customer_contact'] ?? 'Not provided'); ?>';
            const validUntil = document.getElementById('valid_until').value || '<?php echo htmlspecialchars($quotationData['valid_until'] ?? ''); ?>';
            const notes = document.getElementById('notes').value || '<?php echo htmlspecialchars($quotationData['notes'] ?? 'No additional notes provided.'); ?>';
            const status = document.getElementById('status').value || '<?php echo htmlspecialchars($quotationData['status'] ?? 'pending'); ?>';

            let subtotal = 0;
            const items = [];
            const itemRows = document.querySelectorAll('.item-row');
            itemRows.forEach((row, index) => {
                const qty = parseInt(row.querySelector(`input[name="item_qty_${index + 1}"]`)?.value || 0);
                const itemName = row.querySelector(`input[name="item_name_${index + 1}"]`)?.value || 'Not provided';
                const unitPrice = parseFloat(row.querySelector(`input[name="unit_price_${index + 1}"]`)?.value || 0);
                if (qty > 0 && itemName && unitPrice > 0) {
                    items.push({ qty, itemName, unitPrice });
                    subtotal += qty * unitPrice;
                }
            });

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

            document.getElementById('preview-customer-name').textContent = customerName;
            document.getElementById('preview-customer-contact').textContent = customerContact;
            document.getElementById('preview-valid-until').textContent = validUntil;
            document.getElementById('preview-valid-until-footer').textContent = validUntil;
            document.getElementById('preview-notes').textContent = notes;
            document.getElementById('preview-status').textContent = status.charAt(0).toUpperCase() + status.slice(1);

            const previewItems = document.getElementById('preview-items');
            previewItems.innerHTML = '';
            items.forEach((item, index) => {
                const total = (item.qty * item.unitPrice).toFixed(2);
                previewItems.innerHTML += `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${item.itemName}</td>
                        <td>${item.qty}</td>
                        <td>MWK ${item.unitPrice.toFixed(2)}</td>
                        <td>MWK ${total}</td>
                    </tr>
                `;
            });

            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() {
            const form = document.getElementById('quotationForm');
            form.addEventListener('submit', function(event) {
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                const items = document.querySelectorAll('.item-row');
                let validItems = false;
                items.forEach((item, i) => {
                    const qty = parseInt(item.querySelector(`input[name="item_qty_${i + 1}"]`)?.value || 0);
                    const unitPrice = parseFloat(item.querySelector(`input[name="unit_price_${i + 1}"]`)?.value || 0);
                    const itemName = item.querySelector(`input[name="item_name_${i + 1}"]`)?.value || '';
                    if (qty > 0 && unitPrice > 0 && itemName.trim() !== '') {
                        validItems = true;
                    }
                });
                if (!validItems) {
                    event.preventDefault();
                    alert('Please add at least one valid item with quantity, name, and unit price.');
                }
                form.classList.add('was-validated');
            });


            calculateTotal();
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
