<?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 {
    $bill_id      = (int)($_POST['bill_id'] ?? 0);
    $payment_date = $_POST['payment_date'] ?? '';
    $amount       = (float)($_POST['amount'] ?? 0);
    $method       = $_POST['method'] ?? 'Cash';
    $reference_no = trim($_POST['reference_no'] ?? '');
    $remarks      = trim($_POST['remarks'] ?? '');

    if ($bill_id <= 0 || !$payment_date || $amount <= 0) {
        throw new Exception("Missing required fields.");
    }

    $ap = new Ap();
    $success = $ap->addPayment([
        'bill_id'      => $bill_id,
        'payment_date' => $payment_date,
        'amount'       => $amount,
        'method'       => $method,
        'reference_no' => $reference_no,
        'remarks'      => $remarks,
    ]);

    // Optional: update bill status if fully paid
    if ($success) {
        $pdo = Database::getConnection();
        $stmt = $pdo->prepare("SELECT SUM(amount) FROM ap_payments WHERE bill_id=?");
        $stmt->execute([$bill_id]);
        $paid = (float)$stmt->fetchColumn();

        $stmt = $pdo->prepare("SELECT total_amount+gst_amount FROM ap_bills WHERE id=?");
        $stmt->execute([$bill_id]);
        $total = (float)$stmt->fetchColumn();

        $status = $paid >= $total ? 'paid' : ($paid > 0 ? 'partial' : 'unpaid');
        $pdo->prepare("UPDATE ap_bills SET status=? WHERE id=?")->execute([$status, $bill_id]);
    }

    echo json_encode([
        'status' => $success ? 'success' : 'error',
        'message' => $success ? 'Payment recorded successfully.' : 'Failed to record payment.'
    ]);
} catch (Throwable $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
