<?php
declare(strict_types=1);

require_once __DIR__ . '/../../../app/Config/config.php';
require_once __DIR__ . '/../../../app/Config/functions.php';
require_once __DIR__ . '/../../../app/Models/Ap.php';

require_login();

header('Content-Type: application/json');

try {
    $id = (int)($_POST['id'] ?? 0);

    if ($id <= 0) {
        throw new Exception("Invalid bill ID.");
    }

    $pdo = Database::getConnection();
    $pdo->beginTransaction();

    // Check if bill exists
    $stmt = $pdo->prepare("SELECT bill_no FROM ap_bills WHERE id=?");
    $stmt->execute([$id]);
    $bill = $stmt->fetch();

    if (!$bill) {
        throw new Exception("Bill not found.");
    }

    // Delete related payments first (to maintain referential integrity)
    $stmt = $pdo->prepare("DELETE FROM ap_payments WHERE bill_id=?");
    $stmt->execute([$id]);

    // Delete bill record
    $stmt = $pdo->prepare("DELETE FROM ap_bills WHERE id=?");
    $stmt->execute([$id]);

    $pdo->commit();

    echo json_encode([
        'status' => 'success',
        'message' => "Bill #{$bill['bill_no']} deleted successfully."
    ]);

} catch (Throwable $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
