<?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 payment ID.");
    }

    $pdo = Database::getConnection();

    // Retrieve bill_id before deleting
    $stmt = $pdo->prepare("SELECT bill_id FROM ap_payments WHERE id=?");
    $stmt->execute([$id]);
    $bill_id = (int)$stmt->fetchColumn();

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

    // Update bill status after deletion
    $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', 'message' => 'Payment deleted successfully.']);
} catch (Throwable $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
