<?php  
include("includes/db_config.php"); 

if(isset($_POST["cidd"])) {  
    $customer_id = $_POST["cidd"];

    // Use prepared statements to prevent SQL injection
    $query = $conn->prepare("SELECT COALESCE(SUM(total_amt), 0) as ttl, COALESCE(SUM(received_amount), 0) as paid_amt FROM ah_purchase_details WHERE customer_id = ?");
    $query->bind_param("s", $customer_id);
    $query->execute();
    $result = $query->get_result();
    $rows = $result->fetch_assoc();
    
    $sql_query = $conn->prepare("SELECT COALESCE(SUM(received_amonut), 0) as rttl FROM ah_purchase_payment_out WHERE customer_id = ?");
    $sql_query->bind_param("s", $customer_id);
    $sql_query->execute();
    $result2 = $sql_query->get_result();
    $row = $result2->fetch_assoc();

    // Ensure values are not null to prevent warnings
    $total_amt = $rows['ttl'] ?? 0;
    $paid_amt = $row['rttl'] ?? 0;
    $balance_amt = $total_amt - $paid_amt;

    // Return JSON response
    echo json_encode([
        'total_rs' => "Rs: " . number_format($balance_amt, 2),
        'total_amt' => number_format($total_amt, 2),
        'paid_amt' => number_format($paid_amt, 2)
    ]);
}  
?>
