<?php
session_start();
include_once('../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

header('Content-Type: application/json');

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $paymentId = (int)$_GET['id'];
    
    $query = "SELECT p.*, c.CustomerName, c.Mobile, c.Area, 
                     u1.FullName as CreatedByName, u2.FullName as UpdatedByName
              FROM tblcustomerpayments p
              LEFT JOIN tblcustomers c ON p.CustomerID = c.ID
              LEFT JOIN tblusers u1 ON p.CreatedBy = u1.ID
              LEFT JOIN tblusers u2 ON p.UpdatedBy = u2.ID
              WHERE p.ID = $paymentId AND p.IsActive = 1";
    
    $result = mysqli_query($con, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $payment = mysqli_fetch_assoc($result);
        echo json_encode(['success' => true, 'payment' => $payment]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Payment not found']);
    }
} elseif (isset($_GET['customer_id']) && is_numeric($_GET['customer_id'])) {
    $customerId = (int)$_GET['customer_id'];
    
    $query = "SELECT p.*, c.CustomerName 
              FROM tblcustomerpayments p
              LEFT JOIN tblcustomers c ON p.CustomerID = c.ID
              WHERE p.CustomerID = $customerId AND p.IsActive = 1
              ORDER BY p.TransactionDate DESC, p.CreatedDate DESC";
    
    $result = mysqli_query($con, $query);
    $payments = [];
    
    if ($result) {
        while ($row = mysqli_fetch_assoc($result)) {
            $payments[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'payments' => $payments]);
} elseif (isset($_GET['balance']) && is_numeric($_GET['balance'])) {
    $customerId = (int)$_GET['balance'];
    
    // Calculate customer balance (Credits - Debits)
    $balanceQuery = "SELECT 
        COALESCE(SUM(CASE WHEN TransactionType = 'Credit' THEN Amount ELSE 0 END), 0) as TotalCredits,
        COALESCE(SUM(CASE WHEN TransactionType = 'Debit' THEN Amount ELSE 0 END), 0) as TotalDebits,
        (COALESCE(SUM(CASE WHEN TransactionType = 'Credit' THEN Amount ELSE 0 END), 0) - 
         COALESCE(SUM(CASE WHEN TransactionType = 'Debit' THEN Amount ELSE 0 END), 0)) as Balance
        FROM tblcustomerpayments 
        WHERE CustomerID = $customerId AND IsActive = 1 AND Status = 'Completed'";
    
    $result = mysqli_query($con, $balanceQuery);
    
    if ($result) {
        $balance = mysqli_fetch_assoc($result);
        echo json_encode(['success' => true, 'balance' => $balance]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Error calculating balance']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
}
?>
