<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require "db.php";

/* =========================================================
   RECEIVE PAYMENT (POST ONLY)
========================================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['receive_payment'])) {

    $sale_id = (int)$_POST['sale_id'];
    $amount  = (float)$_POST['amount'];
    $method  = mysqli_real_escape_string($conn, $_POST['method']);
    $remarks = mysqli_real_escape_string($conn, $_POST['remarks']);

    $sale = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT s.customer_id, c.cnic
        FROM hps_sales s
        JOIN hps_customers c ON c.id=s.customer_id
        WHERE s.id=$sale_id
        LIMIT 1
    "));

    if (!$sale || $amount <= 0) {
        header("Location: hps_customer_payment.php");
        exit;
    }

    /* Outstanding for this sale (DR - CR) */
    $balRow = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT IFNULL(SUM(dr),0) - IFNULL(SUM(cr),0) bal
        FROM hps_customer_ledger
        WHERE ref_id=$sale_id
    "));
    $bal = (float)($balRow['bal'] ?? 0);

    if ($amount > $bal) $amount = $bal;
    if ($amount <= 0) {
        header("Location: hps_customer_payment.php?cnic=".$sale['cnic']);
        exit;
    }

    /* Decide payment type */
    $paidCount = (int)(mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT COUNT(*) c
        FROM hps_customer_ledger
        WHERE ref_id=$sale_id
          AND ref_type IN ('DOWNPAYMENT','INSTALLMENT')
    "))['c'] ?? 0);

    $pay_type = ($paidCount === 0) ? 'DOWNPAYMENT' : 'INSTALLMENT';

    /* Save payment */
    mysqli_query($conn,"
        INSERT INTO hps_payments
        (sale_id, pay_date, amount, pay_type, method, remarks)
        VALUES
        ($sale_id, CURDATE(), $amount, '$pay_type', '$method', '$remarks')
    ");
    $pay_id = (int)mysqli_insert_id($conn);

    /* Ledger CR entry */
    mysqli_query($conn,"
        INSERT INTO hps_customer_ledger
        (customer_id, trans_date, description, dr, cr, ref_type, ref_id)
        VALUES
        (
            {$sale['customer_id']},
            CURDATE(),
            '$pay_type Received',
            0,
            $amount,
            '$pay_type',
            $sale_id
        )
    ");

    header("Location: hps_customer_payment.php?cnic=".$sale['cnic']."&print_pay_id=".$pay_id);
    exit;
}

/* =========================================================
   CUSTOMER LIST
========================================================= */
$cnic = $_GET['cnic'] ?? '';
$print_pay_id = (int)($_GET['print_pay_id'] ?? 0);

if ($cnic === '') {

    $customers = mysqli_query($conn,"
        SELECT c.*,
               IFNULL(SUM(l.dr)-SUM(l.cr),0) outstanding
        FROM hps_customers c
        LEFT JOIN hps_customer_ledger l ON l.customer_id=c.id
        GROUP BY c.id
        ORDER BY c.name
    ");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Customer Installment Module</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container py-4">

<h4 class="mb-3">💳 Customer Installment Module</h4>

<input type="text" class="form-control mb-2" placeholder="Search customer..."
onkeyup="filterTable(this.value)">

<table class="table table-sm table-bordered">
<thead class="table-dark">
<tr>
<th>Name</th><th>Mobile</th><th>CNIC</th><th>Outstanding</th><th>Action</th>
</tr>
</thead>
<tbody id="custTable">
<?php while($r=mysqli_fetch_assoc($customers)): ?>
<tr>
<td><?=$r['name']?></td>
<td><?=$r['mobile']?></td>
<td><?=$r['cnic']?></td>
<td><?=number_format($r['outstanding'])?></td>
<td><a href="?cnic=<?=$r['cnic']?>" class="btn btn-primary btn-sm">View</a></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>

<script>
function filterTable(val){
    val = val.toLowerCase();
    document.querySelectorAll("#custTable tr").forEach(tr=>{
        tr.style.display = tr.innerText.toLowerCase().includes(val) ? "" : "none";
    });
}
</script>
</body>
</html>
<?php exit; }

/* =========================================================
   CUSTOMER DETAIL
========================================================= */
$cust = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT * FROM hps_customers
    WHERE cnic='".mysqli_real_escape_string($conn,$cnic)."'
    LIMIT 1
"));
if (!$cust) die("Customer not found");

/* =========================================================
   RECEIPT PRINT
========================================================= */
if ($print_pay_id > 0) {

    $rec = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT p.*, s.sale_no
        FROM hps_payments p
        JOIN hps_sales s ON s.id=p.sale_id
        WHERE p.id=$print_pay_id
        LIMIT 1
    "));
    if (!$rec) {
        header("Location: hps_customer_payment.php?cnic=".$cust['cnic']);
        exit;
    }

    $outstanding = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT IFNULL(SUM(dr)-SUM(cr),0) bal
        FROM hps_customer_ledger
        WHERE customer_id={$cust['id']}
    "))['bal'] ?? 0;
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Payment Receipt</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<style>@media print{.no-print{display:none}}</style>
</head>
<body onload="window.print()">
<div class="container py-4">
<h5>💳 Payment Receipt</h5>
<p><b>Date:</b> <?=$rec['pay_date']?></p>
<p><b>Customer:</b> <?=$cust['name']?> (<?=$cust['cnic']?>)</p>
<p><b>Sale No:</b> <?=$rec['sale_no']?></p>
<p><b>Amount:</b> <?=number_format($rec['amount'])?></p>
<p><b>Type:</b> <?=$rec['pay_type']?></p>
<p><b>Method:</b> <?=$rec['method']?></p>
<hr>
<p><b>Outstanding:</b> <?=number_format($outstanding)?></p>
</div>
</body>
</html>
<?php exit; }

/* =========================================================
   SUMMARY
========================================================= */
$sum = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT IFNULL(SUM(dr),0) dr, IFNULL(SUM(cr),0) cr
    FROM hps_customer_ledger
    WHERE customer_id={$cust['id']}
"));

$total_sale = (float)$sum['dr'];
$paid = (float)$sum['cr'];
$outstanding = $total_sale - $paid;

/* =========================================================
   ACTIVE SALE
========================================================= */
$activeSale = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT s.id, s.sale_no
    FROM hps_sales s
    JOIN hps_customer_ledger l ON l.ref_id=s.id
    WHERE s.customer_id={$cust['id']}
      AND s.status='Approved'
    GROUP BY s.id
    HAVING IFNULL(SUM(l.dr)-SUM(l.cr),0) > 0
    ORDER BY s.id DESC
    LIMIT 1
"));

$default_receive = 0;
$sale_id = 0;

if ($activeSale) {
    $sale_id = (int)$activeSale['id'];

    $sale_out = (float)(mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT IFNULL(SUM(dr)-SUM(cr),0) bal
        FROM hps_customer_ledger
        WHERE ref_id=$sale_id
    "))['bal'] ?? 0);

    $inst = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT MAX(monthly_installment) mi
        FROM hps_sale_items
        WHERE sale_id=$sale_id
    "));
    $default_receive = min((float)$inst['mi'], $sale_out);
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Customer Installments</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container py-4">

<h4>💳 Customer Installment Report</h4>

<div class="card mb-3">
<div class="card-body">
<b>Customer:</b> <?=$cust['name']?><br>
<b>CNIC:</b> <?=$cust['cnic']?><br>
<b>Total:</b> <?=number_format($total_sale)?><br>
<b>Paid:</b> <?=number_format($paid)?><br>
<b>Outstanding:</b> <?=number_format($outstanding)?>
</div>
</div>

<?php if($activeSale): ?>
<div class="card mb-3">
<div class="card-header">Receive Payment</div>
<div class="card-body">
<form method="post" class="row g-2">
<input type="hidden" name="sale_id" value="<?=$sale_id?>">
<div class="col-md-3">
<input type="number" step="0.01" name="amount" value="<?=$default_receive?>" class="form-control" required>
</div>
<div class="col-md-3">
<select name="method" class="form-select">
<option>Cash</option>
<option>Bank</option>
<option>Cheque</option>
</select>
</div>
<div class="col-md-4">
<input type="text" name="remarks" class="form-control" placeholder="Remarks">
</div>
<div class="col-md-2">
<button name="receive_payment" class="btn btn-success w-100">Receive</button>
</div>
</form>
</div>
</div>
<?php endif; ?>

</div>
</body>
</html>
