<?php
require_once "../config/auth.php";
require_once "../config/db.php";
require_once "../config/helpers.php";

require_once "../includes/header.php";
require_once "../includes/sidebar.php";
require_once "../includes/topbar.php";

$id = (int) ($_GET['id'] ?? 0);

if(!$id){
    die("Invalid Invoice");
}

// ================= INVOICE =================
$invoice = $conn->query("
SELECT * FROM invoices WHERE id = $id
")->fetch_assoc();

if(!$invoice){
    die("Invoice not found");
}

// ================= CUSTOMERS =================
$customers = $conn->query("SELECT id,name FROM customers");

// ================= SELECTED SERVICES =================
$selectedServices = [];
$res = $conn->query("
SELECT service_id FROM invoice_items WHERE invoice_id = $id
");

while($row = $res->fetch_assoc()){
    $selectedServices[] = $row['service_id'];
}

// ================= CUSTOMER SERVICES =================
$services = $conn->query("
SELECT * FROM services 
WHERE customer_id = {$invoice['customer_id']}
");
?>

<div class="main-content">
<div class="col-lg-12">

<div class="topbar">
    <h5>Edit Invoice</h5>
</div>

<div class="p-4">

<form method="POST" action="../actions/update_invoice.php">

<input type="hidden" name="id" value="<?= $invoice['id'] ?>">

<!-- CUSTOMER -->
<div class="mb-3">
<label>Customer *</label>
<select name="customer_id" class="form-control" required>
<?php while($c = $customers->fetch_assoc()){ ?>
<option value="<?= $c['id'] ?>"
<?= ($c['id'] == $invoice['customer_id']) ? 'selected' : '' ?>>
<?= e($c['name']) ?>
</option>
<?php } ?>
</select>
</div>

<!-- DATE -->
<div class="mb-3">
<label>Invoice Date *</label>
<input type="date" name="invoice_date" class="form-control"
value="<?= $invoice['invoice_date'] ?>" required>
</div>

<!-- DUE DATE -->
<div class="mb-3">
<label>Due Date *</label>
<input type="date" name="due_date" class="form-control"
value="<?= $invoice['due_date'] ?>" required>
</div>

<!-- SERVICES -->
<div class="mb-3">
<label>Select Services *</label>

<?php while($s = $services->fetch_assoc()){ ?>

<div class="form-check">
    <input class="form-check-input" type="checkbox" 
           name="services[]" value="<?= $s['id'] ?>"
           <?= in_array($s['id'], $selectedServices) ? 'checked' : '' ?>>

    <label class="form-check-label">
        <?= !empty($s['service_name']) ? $s['service_name'] : ucfirst($s['type']) ?>
        - ₹<?= $s['amount'] ?>
    </label>
</div>

<?php } ?>

</div>

<button class="btn btn-primary">Update Invoice</button>

</form>

</div>
</div>
</div>

<?php require_once "../includes/footer.php"; ?>
