<?php
include_once('../header.php');

// Check if user is logged in
if (!check_login()) {
    header("Location: " . WEB_URL . "logout.php");
    exit();
}

// Process the form submission
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Sanitize and serialize POST data
    $data = post_input_serilization();

    // Fetch the rent record for the given rent_id
    $rent_result = $link->query("SELECT * FROM service_fee WHERE id = " . intval($data['rent_id']));
    $rent = mysqli_fetch_assoc($rent_result);

    if (!$rent) {
        $_SESSION["message"] = "Error Saving Payment";
        $_SESSION["message_type"] = "error";
        header("Location: " . WEB_URL . "service_fee/servicelist.php");
        exit();
    }

    // Start transaction
    $link->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);

    $rent_id = $rent['id'];
    $total_rent = floatval($rent['total_rent']);
    $amt_paid = floatval($rent['amt_paid']);
    $amount_paid = floatval($data['amount_paid']);

    // Check if the payment exceeds the total rent amount
    if ($amount_paid + $amt_paid >= $total_rent) {
        // Payment scenario: update the rent as fully paid
        $link->query("UPDATE service_fee SET amt_paid = $total_rent, bill_status = 1 WHERE id = $rent_id");
        $link->query("INSERT INTO tenant_service_accounts (tid, rid, trans_type, description, transaction_amt, added_by) 
                      VALUES (" . intval($rent['tid']) . ", $rent_id, 'debit', 'Rent Payment From Tenant - Tenant Overpaid', $amount_paid, " . intval($_SESSION['user_id']) . ")");
    } else {
        // Normal payment: update the amount paid
        $link->query("UPDATE service_fee SET amt_paid = amt_paid + $amount_paid WHERE id = $rent_id");
        $link->query("INSERT INTO tenant_service_accounts (tid, rid, trans_type, description, transaction_amt, added_by) 
                      VALUES (" . intval($rent['tid']) . ", $rent_id, 'debit', 'Rent Payment From Tenant', $amount_paid, " . intval($_SESSION['user_id']) . ")");
    }
    

    // Log the payment update
    $link->query("INSERT INTO service_payment_updates (rent_id, amount, added_by) 
                  VALUES ($rent_id, $amount_paid, " . intval($_SESSION['user_id']) . ")");

    // Commit the transaction
    if ($link->commit()) {
        $_SESSION["message"] = "Payment Added Successfully";
        header("Location: " . WEB_URL . "service_fee/servicelist.php");
        exit();
    } else {
        $_SESSION["message"] = "Failed to Add Payment";
        header("Location: " . WEB_URL . "service_fee/servicelist.php");
        exit();
    }
} else {
    // Redirect if not a POST request
    header("Location: " . WEB_URL . "service_fee/servicelist.php");
    exit();
}
?>
