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

$id          = (int) $_POST['id'];
$customer_id = (int) $_POST['customer_id'];
$date        = $_POST['invoice_date'];
$due_date    = $_POST['due_date'];
$services    = $_POST['services'] ?? [];

if(!$id || !$customer_id || !$date || !$due_date || empty($services)){
    die("Missing data");
}

// UPDATE INVOICE
$stmt = $conn->prepare("
UPDATE invoices 
SET customer_id=?, invoice_date=?, due_date=? 
WHERE id=?
");

$stmt->bind_param("issi", $customer_id, $date, $due_date, $id);
$stmt->execute();

// DELETE OLD ITEMS
$conn->query("DELETE FROM invoice_items WHERE invoice_id=$id");

$total = 0;

// INSERT NEW ITEMS
foreach($services as $sid){

    $sid = (int)$sid;

    $res = $conn->query("SELECT * FROM services WHERE id=$sid")->fetch_assoc();

    if(!$res) continue;

    $amount = $res['amount'];
    $total += $amount;

    $stmt = $conn->prepare("
    INSERT INTO invoice_items (invoice_id, service_id, amount)
    VALUES (?, ?, ?)
    ");

    $stmt->bind_param("iid", $id, $sid, $amount);
    $stmt->execute();
}

// UPDATE TOTAL
$stmt = $conn->prepare("UPDATE invoices SET total=? WHERE id=?");
$stmt->bind_param("di", $total, $id);
$stmt->execute();

header("Location: ../pages/invoices.php");
exit;
