<?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);
    $bill_no      = trim($_POST['bill_no'] ?? '');
    $vendor_id    = (int)($_POST['vendor_id'] ?? 0);
    $bill_date    = $_POST['bill_date'] ?? '';
    $due_date     = $_POST['due_date'] ?? null;
    $total_amount = (float)($_POST['total_amount'] ?? 0);
    $gst_amount   = (float)($_POST['gst_amount'] ?? 0);
    $remarks      = trim($_POST['remarks'] ?? '');

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

    $ap = new Ap();
    $success = $ap->updateBill($id, [
        'bill_no' => $bill_no,
        'vendor_id' => $vendor_id,
        'bill_date' => $bill_date,
        'due_date' => $due_date,
        'total_amount' => $total_amount,
        'gst_amount' => $gst_amount,
        'remarks' => $remarks,
    ]);

    echo json_encode([
        'status' => $success ? 'success' : 'error',
        'message' => $success ? 'Bill updated successfully.' : 'Failed to update bill.'
    ]);
} catch (Throwable $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
