<?php
include 'db.php';

// Load quotations to select
$quotations = $conn->query("SELECT id, partner_name FROM quotations ORDER BY id DESC");

// If quotation selected, load its data
$quotationData = null;
$quotationItems = [];
if (isset($_GET['quotation_id'])) {
    $qid = intval($_GET['quotation_id']);
    $quotationData = $conn->query("SELECT * FROM quotations WHERE id=$qid")->fetch_assoc();
    $quotationItems = $conn->query("SELECT * FROM quotation_items WHERE quotation_id=$qid");
}

// Handle invoice creation
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $quotation_id = !empty($_POST['quotation_id']) ? intval($_POST['quotation_id']) : null;
    $partner_name = $_POST['partner_name'];
    $partner_address = $_POST['partner_address'];
    $sst_enabled = isset($_POST['sst_enabled']) ? 1 : 0;

    $stmt = $conn->prepare("INSERT INTO invoices (quotation_id, partner_name, partner_address, sst_enabled) VALUES (?,?,?,?)");
    $stmt->bind_param("issi", $quotation_id, $partner_name, $partner_address, $sst_enabled);
    $stmt->execute();
    $invoice_id = $stmt->insert_id;

    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 invoice_items (invoice_id, description, quantity, unit_price, total) VALUES (?,?,?,?,?)");
        $stmt->bind_param("isidd", $invoice_id, $desc, $qty, $unit_price, $total);
        $stmt->execute();
    }

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

<!DOCTYPE html>
<html>
<head>
    <title>Create Invoice - 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>
            `;
        }
        function loadQuotation() {
            let qid = document.getElementById("quotationSelect").value;
            if (qid) {
                window.location.href = "create_invoice.php?quotation_id=" + qid;
            }
        }
    </script>
</head>
<body class="p-4 bg-light">

<div class="container bg-white p-4 rounded shadow">
    <h3 class="mb-4">Create Invoice</h3>

    <!-- Quotation Selection -->
    <div class="mb-3">
        <label class="form-label">Select Quotation (Optional)</label>
        <select id="quotationSelect" class="form-select" onchange="loadQuotation()">
            <option value="">-- Create Manually --</option>
            <?php while($q = $quotations->fetch_assoc()) { ?>
                <option value="<?php echo $q['id']; ?>" <?php if(isset($_GET['quotation_id']) && $_GET['quotation_id']==$q['id']) echo 'selected'; ?>>
                    Quotation #<?php echo $q['id']; ?> - <?php echo htmlspecialchars($q['partner_name']); ?>
                </option>
            <?php } ?>
        </select>
    </div>

    <!-- Invoice Form -->
    <form method="post">
        <input type="hidden" name="quotation_id" value="<?php echo $_GET['quotation_id'] ?? ''; ?>">

        <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 $quotationData['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 $quotationData['partner_address'] ?? ''; ?></textarea>
        </div>

        <div class="mb-3 form-check">
            <input type="checkbox" name="sst_enabled" class="form-check-input" 
                <?php echo (!empty($quotationData['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 if ($quotationItems && $quotationItems->num_rows > 0) { 
                    while ($item = $quotationItems->fetch_assoc()) { ?>
                        <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 } } else { ?>
                        <tr>
                            <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>
                        </tr>
                <?php } ?>
            </tbody>
        </table>
        <button type="button" class="btn btn-sm btn-secondary" onclick="addRow()">+ Add Item</button>

        <div class="mt-4">
            <a href="list_invoices.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Save Invoice</button>
        </div>
    </form>
</div>

</body>
</html>
