<?php
session_start();
include('dbcon.php');

$id = $_POST['id'];

$paid_amount = $_POST['paid_amount'];
$payment_date = $_POST['payment_date'];
$payment_gateway = $_POST['payment_gateway'];
$due_date = $_POST['due_date'];

// Fetch old payment data
$pay = mysqli_fetch_assoc(mysqli_query($conn,
        "SELECT client_id,total_amount, paid_amount 
         FROM tbl_payment 
         WHERE id='$id'"));

$client_id = $pay['client_id'];
$total_amount = $pay['total_amount'];
$old_paid = $pay['paid_amount'];

// NEW total paid  
$new_paid = $old_paid + $paid_amount;

// New Due Amount
$new_due = $total_amount - $new_paid;

/* -----------------------------------------------------
   1️⃣ UPDATE OLD PAYMENT ROW
------------------------------------------------------*/
$updateQuery = "UPDATE tbl_payment SET 
                    paid_amount='$new_paid',
                    due_amount='$new_due',
                    payment_date='$payment_date',
                    payment_gateway='$payment_gateway',
                    due_date='$due_date'
                WHERE id='$id'";

mysqli_query($conn, $updateQuery);


/* -----------------------------------------------------
   2️⃣ INSERT NEW PAYMENT ENTRY (History)
------------------------------------------------------*/
$insertQuery = "INSERT INTO tbl_payment 
                    (client_id,total_amount,paid_amount,due_amount,payment_date,payment_gateway,due_date)
                VALUES 
                    ('$client_id','$total_amount','$paid_amount','$new_due',
                     '$payment_date','$payment_gateway','$due_date')";

mysqli_query($conn, $insertQuery);


/* -----------------------------------------------------
   3️⃣ SUCCESS MESSAGE
------------------------------------------------------*/
$_SESSION['status'] = "Payment Updated Successfully!";
header("Location: view-payment.php");
exit();

?>
