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

require "db.php";

/* ================= VALIDATE SALE ================= */
if (!isset($_GET['sale_id']) || !is_numeric($_GET['sale_id'])) {
    die("Invalid sale");
}
$sale_id = (int)$_GET['sale_id'];

/* ================= LOAD SALE ================= */
$sale = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT s.*, c.name customer, c.mobile
    FROM hps_sales s
    JOIN hps_customers c ON c.id = s.customer_id
    WHERE s.id = $sale_id
"));
if (!$sale || $sale['status'] !== 'Approved') {
    die("Sale not available for payment");
}

/* ================= LOAD ITEMS ================= */
$items = mysqli_query($conn,"
    SELECT qty, price, down_payment, installments, markup_rate,
           monthly_installment
    FROM hps_sale_items
    WHERE sale_id = $sale_id
");

/* ================= CALCULATIONS ================= */
$cash = $down = $markup = 0;
$monthly = 0;
$totalIns = 0;

while ($row = mysqli_fetch_assoc($items)) {

    $item_price = $row['qty'] * $row['price'];
    $item_down  = $row['down_payment'];
    $financed   = max(0, $item_price - $item_down);

    $item_markup =
        $financed *
        ($row['markup_rate'] / 100) *
        ($row['installments'] / 12);

    $cash   += $item_price;
    $down   += $item_down;
    $markup += $item_markup;

    $monthly  = (float)$row['monthly_installment'];
    $totalIns = (int)$row['installments'] + 1;
}

$markup = round($markup);
$doc    = (float)$sale['documentation_charges'];
$total  = $cash + $markup + $doc;

/* ===== Amount suggested to receive ===== */
$receive_now = $down + $doc;

/* ================= PAID / OUTSTANDING ================= */
$r = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT IFNULL(SUM(cr) - SUM(dr),0) t
    FROM hps_customer_ledger
    WHERE ref_id = $sale_id
"));
$paid = (float)$r['t'];
$outstanding = max(0, $total - $paid);

/* ================= RECEIVE PAYMENT ================= */
$msg = "";
if (isset($_POST['receive'])) {

    $amount  = (float)$_POST['amount'];
    $type    = $_POST['type'];
    $mode    = $_POST['mode'];               // CASHBOOK ADD
    $remarks = trim($_POST['remarks']);

    if ($amount <= 0) {
        $msg = "Invalid amount";
    } else {

        if ($remarks === '') {
            $remarks = strtoupper($type);
        }

        mysqli_query($conn,"
            INSERT INTO hps_customer_ledger
            (customer_id, ref_type, ref_id, cr, description, trans_date, created_at)
            VALUES
            ({$sale['customer_id']}, '$type', $sale_id, $amount,
             '$remarks', CURDATE(), NOW())
        ");

        $pid = mysqli_insert_id($conn);

        /* ================= CASHBOOK POST (ONLY IF CASH) ================= */
        if ($mode === 'CASH') {

            mysqli_query($conn,"
                INSERT INTO hps_cashbook
                (trans_date, description, from_account, to_account, amount, ref_type, ref_id)
                VALUES
                (
                    CURDATE(),
                    'Cash received against Sale ID $sale_id ($type)',
                    NULL,
                    1,
                    $amount,
                    'SALE_RECEIPT',
                    $pid
                )
            ");
        }
        /* ================================================================ */

        header("Location: hps_payment_receipt.php?pid=$pid");
        exit;
    }
}

/* ================= PAYMENT HISTORY ================= */
$history = mysqli_query($conn,"
    SELECT *
    FROM hps_customer_ledger
    WHERE ref_id = $sale_id
    ORDER BY id DESC
");

/* ================= INSTALLMENT SCHEDULE ================= */
$sale_date = $sale['sale_date'];

$paidTotal = (float)mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT IFNULL(SUM(cr),0) total
    FROM hps_customer_ledger
    WHERE ref_id = $sale_id
      AND ref_type = 'INSTALLMENT'
"))['total'];

$today = date('Y-m-d');
$remainingPaid = $paidTotal;
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Receive Payment</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="p-3">

<div class="container">

<h4 class="mb-2">Receive Payment</h4>

<div class="mb-2">
<button class="btn btn-primary"
        data-bs-toggle="modal"
        data-bs-target="#scheduleModal">
    Schedule
</button>

<a href="hps_sale_approved.php" class="btn btn-secondary">Back</a>
</div>

<?php if ($msg): ?>
<div class="alert alert-danger"><?= htmlspecialchars($msg) ?></div>
<?php endif; ?>

<table class="table table-bordered table-sm" style="max-width:700px;">
<tr><th>Total Receivable</th><td><?= number_format($total) ?></td></tr>
<tr><th>Paid</th><td><?= number_format($paid) ?></td></tr>
<tr class="table-warning">
    <th>Outstanding</th>
    <td><b><?= number_format($outstanding) ?></b></td>
</tr>
</table>

<form method="post" style="max-width:700px;">

<div class="mb-2">
    <label>Payment Type</label>
    <select name="type" class="form-control">
        <option value="INSTALLMENT">Installment</option>
        <option value="DOWN">Down Payment</option>
        <option value="DOC">Documentation</option>
    </select>
</div>

<!-- CASHBOOK ADD -->
<div class="mb-2">
    <label>Payment Mode</label>
    <select name="mode" class="form-control">
        <option value="CASH">Cash</option>
        <option value="BANK">Bank</option>
        <option value="CHEQUE">Cheque</option>
    </select>
</div>
<!-- END -->

<div class="mb-2">
    <label>Amount</label>
    <input type="number" name="amount" class="form-control"
           value="<?= $receive_now ?>">
</div>

<div class="mb-2">
    <label>Remarks</label>
    <input type="text" name="remarks" class="form-control">
</div>

<button name="receive" class="btn btn-success">Receive Payment</button>
</form>

<hr>

<h5>Payment History</h5>
<table class="table table-sm table-bordered">
<thead class="table-dark">
<tr>
    <th>Date</th>
    <th>Type</th>
    <th>Remarks</th>
    <th class="text-end">Amount</th>
    <th>Receipt</th>
</tr>
</thead>
<tbody>
<?php while($p=mysqli_fetch_assoc($history)): ?>
<tr>
    <td><?= $p['trans_date'] ?></td>
    <td><?= $p['ref_type'] ?></td>
    <td><?= htmlspecialchars($p['description']) ?></td>
    <td class="text-end"><?= number_format($p['cr']) ?></td>
    <td>
        <a href="hps_payment_receipt.php?pid=<?= $p['id'] ?>"
           target="_blank"
           class="btn btn-sm btn-outline-primary">
           Print
        </a>
    </td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>

<!-- INSTALLMENT MODAL (UNCHANGED) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
