<?php
include('authentication.php');
include('includes/header.php');
include('includes/navbar.php');
include('dbcon.php');

$client_id = $_GET['id'] ?? 0;

// Fetch client info
$client = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM tbl_client WHERE Id='$client_id'"));

// Fetch total paid so far
$payment_summary = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT IFNULL(SUM(paid_amount),0) AS total_paid 
    FROM tbl_payment 
    WHERE client_Id='$client_id'
"));

$total_paid = $payment_summary['total_paid'];
$total_amount = $client['total_amount'];
$due_amount = $total_amount - $total_paid;

// Handle form submission
if (isset($_POST['submit'])) {
    $new_paid = $_POST['paid_amount'];
    $payment_date = $_POST['payment_date'];
    $due_date = $_POST['due_date'];
    $payment_gateway = $_POST['payment_gateway'];

    // New due after this payment
    $updated_due = $total_amount - ($total_paid + $new_paid);

    // INSERT new payment history
    $insert_sql = "INSERT INTO tbl_payment 
                   (client_Id, total_amount, paid_amount, due_amount, payment_date, due_date, payment_gateway)
                   VALUES 
                   ('$client_id', '$total_amount', '$new_paid', '$updated_due', '$payment_date', '$due_date', '$payment_gateway')";

    if (mysqli_query($conn, $insert_sql)) {
        echo "<script>
                alert('Payment recorded successfully!');
                window.location.href='due-payment.php';
              </script>";
    } else {
        echo "Error: " . mysqli_error($conn);
    }
}
?>

<div class="inquiry-container">
<h3 class="text-center">Add Payment for <?= $client['cust_name']; ?></h3>

<form action="" method="POST">
    <label>Total Amount</label>
    <input type="text" value="<?= $total_amount ?>" readonly>

    <label>Total Paid So Far</label>
    <input type="text" value="<?= $total_paid ?>" readonly>

    <label>Due Amount</label>
    <input type="text" value="<?= $due_amount ?>" readonly>

    <label>New Payment</label>
    <input type="number" name="paid_amount" placeholder="Enter Paid Amount" required>

    <label>Payment Date</label>
    <input type="date" name="payment_date" required>

    <label>Due Date</label>
    <input type="date" name="due_date">

    <label>Payment Gateway</label>
    <select name="payment_gateway" required>
        <option value="Cash">Cash</option>
        <option value="Google Pay">Google Pay</option>
        <option value="PhonePe">PhonePe</option>
        <option value="Bank Transfer">Bank Transfer</option>
    </select>

    <button class="" name="submit">Add Payment</button>
</form>
</div>

<?php
include('includes/scripts.php');
include('includes/footer.php');
?>
