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

if($_SERVER['REQUEST_METHOD'] !== 'POST'){
    die("Invalid request");
}

// ================= INPUT =================
$customer_id = (int) ($_POST['customer_id'] ?? 0);
$invoice_date = $_POST['invoice_date'] ?? '';
$due_date = $_POST['due_date'] ?? '';
$services = $_POST['service_id'] ?? []; // ✅ FIXED

// ================= VALIDATION =================
if(!$customer_id || !$invoice_date || !$due_date || empty($services)){
    die("Missing data");
}

// ================= START TRANSACTION =================
$conn->begin_transaction();

try{

    // ================= CREATE INVOICE =================
    $stmt = $conn->prepare("
    INSERT INTO invoices (customer_id, invoice_date, due_date, total, payment_status)
    VALUES (?, ?, ?, 0, 'pending')
    ");
    $stmt->bind_param("iss", $customer_id, $invoice_date, $due_date);
    $stmt->execute();

    $invoice_id = $conn->insert_id;

    $total = 0;

    // ================= PREPARE SERVICE FETCH =================
    $serviceStmt = $conn->prepare("SELECT service_name, type, amount FROM services WHERE id=?");

    // ================= INSERT ITEM =================
    $itemStmt = $conn->prepare("
    INSERT INTO invoice_items (invoice_id, service_id, description, amount)
    VALUES (?, ?, ?, ?)
    ");

    // ================= LOOP =================
    foreach($services as $sid){

        $sid = (int)$sid;

        // fetch service
        $serviceStmt->bind_param("i", $sid);
        $serviceStmt->execute();
        $res = $serviceStmt->get_result()->fetch_assoc();

        if(!$res) continue;

        // description
        $description = trim($res['service_name']);

        if(empty($description)){
            $description = ucfirst($res['type']) ?: "Service Item";
        }

        $amount = (float)$res['amount'];
        $total += $amount;

        // insert item
        $itemStmt->bind_param("iisd", $invoice_id, $sid, $description, $amount);
        $itemStmt->execute();

        // update service last billed
        $update = $conn->prepare("UPDATE services SET last_billed=? WHERE id=?");
        $update->bind_param("si", $invoice_date, $sid);
        $update->execute();
    }

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

    // ================= COMMIT =================
    $conn->commit();

    header("Location: ../pages/add_invoice.php?success=1");
    exit;

}catch(Exception $e){

    // rollback on error
    $conn->rollback();
    die("Error saving invoice: " . $e->getMessage());
}