<?php
include 'db.php';

if (!isset($_GET['id'])) {
    die("Quotation ID is required.");
}
$id = intval($_GET['id']);

// Fetch quotation
$qry = $conn->prepare("SELECT * FROM quotations WHERE id=?");
$qry->bind_param("i", $id);
$qry->execute();
$quotation = $qry->get_result()->fetch_assoc();

if (!$quotation) {
    die("Quotation not found!");
}

// Fetch quotation items
$items = [];
$result = $conn->query("SELECT * FROM quotation_items WHERE quotation_id=$id");
while ($row = $result->fetch_assoc()) {
    $items[] = $row;
}

// Handle update form submit
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $partner_name = $_POST['partner_name'];
    $partner_address = $_POST['partner_address'];
    $sst_enabled = isset($_POST['sst_enabled']) ? 1 : 0;

    // Update main quotation
    $stmt = $conn->prepare("UPDATE quotations SET partner_name=?, partner_address=?, sst_enabled=? WHERE id=?");
    $stmt->bind_param("ssii", $partner_name, $partner_address, $sst_enabled, $id);
    $stmt->execute();

    // Delete old items
    $conn->query("DELETE FROM quotation_items WHERE quotation_id=$id");

    // Insert updated items
    foreach ($_POST['description'] as $i => $desc) {
        if (trim($desc) == '') continue;

        $qty = $_POST['quantity'][$i];
        $unit_price = $_POST['unit_price'][$i];
        $total = $qty * $unit_price;

        $stmt = $conn->prepare("INSERT INTO quotation_items (quotation_id, description, quantity, unit_price, total) VALUES (?,?,?,?,?)");
        $stmt->bind_param("isidd", $id, $desc, $qty, $unit_price, $total);
        $stmt->execute();
    }

    header("Location: view_quotation.php?id=$id");
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Quotation #<?php echo $id; ?> - VSONIC ENGINEERING</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script>
        function addRow() {
            let table = document.getElementById("itemsTable").getElementsByTagName('tbody')[0];
            let newRow = table.insertRow();

            newRow.innerHTML = `
                <td><input type="text" name="description[]" class="form-control"></td>
                <td><input type="number" name="quantity[]" class="form-control" min="1" value="1"></td>
                <td><input type="number" name="unit_price[]" class="form-control" step="0.01" value="0"></td>
                <td class="text-center"><button type="button" class="btn btn-danger btn-sm" onclick="this.closest('tr').remove()">X</button></td>
            `;
        }
    </script>
</head>
<body class="p-4 bg-light">

<div class="container bg-white p-4 rounded shadow">
    <h3 class="mb-4">Edit Quotation #<?php echo $id; ?></h3>

    <form method="post">

        <div class="mb-3">
            <label class="form-label">Business Partner Name</label>
            <input type="text" name="partner_name" class="form-control" required value="<?php echo htmlspecialchars($quotation['partner_name']); ?>">
        </div>

        <div class="mb-3">
            <label class="form-label">Business Partner Address</label>
            <textarea name="partner_address" class="form-control" rows="3" required><?php echo htmlspecialchars($quotation['partner_address']); ?></textarea>
        </div>

        <div class="mb-3 form-check">
            <input type="checkbox" name="sst_enabled" class="form-check-input" <?php echo $quotation['sst_enabled'] ? 'checked' : ''; ?>>
            <label class="form-check-label">Apply SST (8%)</label>
        </div>

        <h5>Items</h5>
        <table class="table table-bordered" id="itemsTable">
            <thead>
                <tr>
                    <th>Description</th>
                    <th width="100">Quantity</th>
                    <th width="150">Unit Price</th>
                    <th width="50">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($items as $item) { ?>
                <tr>
                    <td><input type="text" name="description[]" class="form-control" value="<?php echo htmlspecialchars($item['description']); ?>"></td>
                    <td><input type="number" name="quantity[]" class="form-control" min="1" value="<?php echo $item['quantity']; ?>"></td>
                    <td><input type="number" name="unit_price[]" class="form-control" step="0.01" value="<?php echo $item['unit_price']; ?>"></td>
                    <td class="text-center"><button type="button" class="btn btn-danger btn-sm" onclick="this.closest('tr').remove()">X</button></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
        <button type="button" class="btn btn-sm btn-secondary" onclick="addRow()">+ Add Item</button>

        <div class="mt-4">
            <a href="view_quotation.php?id=<?php echo $id; ?>" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Save Changes</button>
        </div>

    </form>
</div>

</body>
</html>
