<?php
require "db.php";

error_reporting(E_ALL);
ini_set('display_errors', 1);

function e($v){
    return htmlspecialchars((string)($v ?? ''));
}

function money($v){
    return number_format((float)$v, 2);
}

/* =========================
   VALIDATION
========================= */
if (!isset($_GET['customer_id']) || !is_numeric($_GET['customer_id'])) {
    die("Customer missing");
}

$customer_id = (int)$_GET['customer_id'];
$from = $_GET['from'] ?? '';
$to   = $_GET['to'] ?? '';

/* =========================
   CUSTOMER
========================= */
$customer = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT *
    FROM hps_customers
    WHERE id = $customer_id
    LIMIT 1
"));
if (!$customer) die("Invalid customer");

/* =========================
   HELPER: UPDATE SCHEDULE STATUS
========================= */
function update_schedule_status($conn, $schedule_id){
    $schedule_id = (int)$schedule_id;
    if($schedule_id <= 0) return;

    $sch = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT id, inst_amount, paid_amount
        FROM hps_installment_schedule
        WHERE id = $schedule_id
        LIMIT 1
    "));

    if(!$sch) return;

    $inst_amount = (float)$sch['inst_amount'];
    $paid_amount = (float)$sch['paid_amount'];

    if($paid_amount <= 0){
        $paid_amount = 0;
        $status = 'Pending';
    }elseif($paid_amount >= $inst_amount){
        $status = 'Paid';
    }else{
        $status = 'Adjusted';
    }

    mysqli_query($conn,"
        UPDATE hps_installment_schedule
        SET paid_amount = $paid_amount,
            status = '$status'
        WHERE id = $schedule_id
    ");
}

/* =========================
   DELETE INSTALLMENT RECEIPT
========================= */
if(isset($_GET['delete_id'])){
    $id = (int)$_GET['delete_id'];

    mysqli_begin_transaction($conn);

    $row = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT * FROM hps_customer_ledger WHERE id=$id
    "));

    if($row && $row['ref_type']=='INSTALLMENT'){

        // delete ledger
        mysqli_query($conn,"DELETE FROM hps_customer_ledger WHERE id=$id");

        // delete from cashbook
        mysqli_query($conn,"
            DELETE FROM hps_cashbook 
            WHERE ref_type='INSTALLMENT' 
            AND ref_id=$id
        ");
    }

    mysqli_commit($conn);

    header("Location: ".$_SERVER['PHP_SELF']."?customer_id=".$customer_id);
    exit;
}

/* =========================
   UPDATE INSTALLMENT RECEIPT
========================= */
if(isset($_POST['update_installment'])){

    $id   = (int)$_POST['id'];
    $date = $_POST['date'];
    $amt  = (float)$_POST['amount'];
    $desc = mysqli_real_escape_string($conn,$_POST['description']);

    mysqli_begin_transaction($conn);

    mysqli_query($conn,"
        UPDATE hps_customer_ledger
        SET 
            trans_date='$date',
            description='$desc',
            cr=$amt
        WHERE id=$id
    ");

    mysqli_query($conn,"
        UPDATE hps_cashbook
        SET 
            trans_date='$date',
            amount=$amt,
            description='$desc'
        WHERE ref_type='INSTALLMENT'
        AND ref_id=$id
    ");

    mysqli_commit($conn);

    header("Location: ".$_SERVER['PHP_SELF']."?customer_id=".$customer_id);
    exit;
}

/* =========================
   SALES INFO AT TOP
========================= */
$salesTop = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT
        GROUP_CONCAT(DISTINCT s.sale_ref ORDER BY s.sale_ref SEPARATOR ', ') AS sale_refs,
        GROUP_CONCAT(DISTINCT p.name ORDER BY p.name SEPARATOR ', ') AS product_names
    FROM hps_sales s
    LEFT JOIN hps_sale_items si ON si.sale_id = s.id
    LEFT JOIN hps_products p ON p.id = si.product_id
    WHERE s.customer_id = $customer_id
      AND s.status = 'Approved'
"));

$sale_refs      = $salesTop['sale_refs'] ?? '';
$product_names  = $salesTop['product_names'] ?? '';

/* =========================
   TOTAL SALE (MATCH SALES REPORT)
========================= */
/* =========================
   TOTAL SALE (INCLUDING DOC)
========================= */

/* =========================
   TOTAL SALE (WITH MARKUP + DOC)
========================= */

$saleRow = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT IFNULL(SUM(
        (
            SELECT IFNULL(SUM(
                (
                    IFNULL(si.price,0)
                    +
                    (
                        (IFNULL(si.price,0) - IFNULL(si.down_payment,0))
                        *
                        ((IFNULL(si.markup_rate,0)/100) * (IFNULL(si.installments,0)/12))
                    )
                )
            ),0)
            FROM hps_sale_items si
            WHERE si.sale_id = s.id
        )
        + IFNULL(s.documentation_charges,0)
    ),0) AS total_sale
    FROM hps_sales s
    WHERE s.customer_id = $customer_id
      AND s.status='Approved'
"));

$total_sale = (float)$saleRow['total_sale'];


/* =========================
   PAYMENTS FROM LEDGER (FINAL FIX)
========================= */
$where = "customer_id = $customer_id AND cr > 0";

if($from != ''){
    $from = mysqli_real_escape_string($conn,$from);
    $where .= " AND trans_date >= '$from'";
}

if($to != ''){
    $to = mysqli_real_escape_string($conn,$to);
    $where .= " AND trans_date <= '$to'";
}

$payments = mysqli_query($conn,"
    SELECT *
    FROM hps_customer_ledger
    WHERE $where
    ORDER BY trans_date, id
");

/* =========================
   CASH ACCOUNTS FOR EDIT
========================= */
$cashAccounts = mysqli_query($conn,"
    SELECT id, account_name, account_type
    FROM hps_cash_accounts
    ORDER BY account_name
");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Customer Statement</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body{ background:#f5f6f8; }
.card-box{
    background:#fff;
    border:1px solid #d9d9d9;
    border-radius:14px;
    box-shadow:0 3px 12px rgba(0,0,0,.08);
}
.top-info{
    font-size:14px;
    line-height:1.6;
}
.table td, .table th{
    vertical-align:middle;
    font-size:13px;
}
.small-muted{
    font-size:12px;
    color:#666;
}
@media print{
    .no-print{ display:none !important; }
    body{ background:#fff; }
    .card-box{
        border:none !important;
        box-shadow:none !important;
    }
}
</style>
</head>
<body>

<div class="container py-4">

    <div class="card-box p-4">

        <div class="d-flex justify-content-between align-items-start mb-3">
            <div>
                <h4 class="mb-1"><?= e($customer['name']) ?></h4>
                <div class="top-info">
                    <div><b>CNIC:</b> <?= e($customer['cnic']) ?></div>
                    <div><b>Mobile:</b> <?= e($customer['mobile']) ?></div>
                    <div><b>Address:</b> <?= e($customer['address']) ?></div>
                    <div><b>Sale Ref:</b> <?= e($sale_refs ?: '-') ?></div>
                    <div><b>Product Name:</b> <?= e($product_names ?: '-') ?></div>
                </div>
            </div>

            <div class="text-end no-print">
                <button onclick="window.print()" class="btn btn-sm btn-secondary">Print</button>
            </div>
        </div>

        <div class="d-flex justify-content-between mb-3">
            <div class="small-muted">
                <b>From:</b> <?= e($from ?: 'Beginning') ?><br>
                <b>To:</b> <?= e($to ?: 'Today') ?>
            </div>
            <div class="small-muted text-end">
                <b>Date:</b> <?= date('Y-m-d') ?>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-bordered table-sm">
                <thead class="table-dark">
                <tr>
                    <th style="width:100px;">Date</th>
                    <th>Description</th>
                    <th style="width:90px;" class="text-end">Debit</th>
                    <th style="width:90px;" class="text-end">Credit</th>
                    <th style="width:100px;" class="text-end">Balance</th>
                    <th style="width:180px;" class="no-print">Action</th>
                </tr>
                </thead>
                <tbody>

                <?php $balance = 0; ?>

                <tr class="table-secondary">
                    <td colspan="4"><b>Opening Balance</b></td>
                    <td class="text-end"><b>0.00</b></td>
                    <td class="no-print"></td>
                </tr>

                <tr>
    <td><?= date('Y-m-d') ?></td>
    <td>
        <b>HP SALE</b>
        <div class="small-muted">Includes Documentation</div>
    </td>
    <td class="text-end"><?= money($total_sale) ?></td>
    <td></td>
    <td class="text-end">
        <?php $balance += $total_sale; echo money($balance); ?>
    </td>
    <td class="no-print"></td>
</tr>

                <?php while($p = mysqli_fetch_assoc($payments)): ?>
<tr>
    <td><?= e($p['trans_date']) ?></td>

    <td>
        <b><?= e($p['description']) ?></b>

        <?php if($p['ref_type'] == 'INSTALLMENT'): ?>
            <div class="small-muted text-success">Installment Received</div>
        <?php endif; ?>

        <?php if($p['ref_type'] == 'DOC'): ?>
            <div class="small-muted text-info">Documentation</div>
        <?php endif; ?>
    </td>

    <td class="text-end"></td>

    <td class="text-end"><?= money($p['cr']) ?></td>

    <td class="text-end">
        <?php
        $balance -= (float)$p['cr'];
        echo money($balance);
        ?>
    </td>

    <td class="no-print">

<?php if($p['ref_type']=='INSTALLMENT'): ?>

<button class="btn btn-sm btn-warning"
onclick="editInstallment(
<?= $p['id'] ?>,
'<?= $p['trans_date'] ?>',
'<?= $p['cr'] ?>',
'<?= htmlspecialchars($p['description']) ?>'
)">
Edit</button>

<a href="?customer_id=<?= $customer_id ?>&delete_id=<?= $p['id'] ?>"
class="btn btn-sm btn-danger"
onclick="return confirm('Delete installment?')">
Delete</a>

<?php endif; ?>

</td>
</tr>
<?php endwhile; ?>

                <tr class="table-dark">
                    <td colspan="4" class="text-end"><b>Closing Balance</b></td>
                    <td class="text-end"><b><?= money($balance) ?></b></td>
                    <td class="no-print"></td>
                </tr>

                </tbody>
            </table>
        </div>

        <div class="mt-3 no-print">
            <a href="hps_customer_statement_select.php" class="btn btn-sm btn-secondary">← Back</a>
        </div>

    </div>
</div>

<!-- =========================
     EDIT MODAL
========================= -->
<div class="modal fade" id="editReceiptModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-dark">
            <form method="post">
                <div class="modal-header bg-primary text-white">
                    <h6 class="modal-title">Edit Installment Receipt</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body">
                    <input type="hidden" name="receipt_id" id="edit_receipt_id">

                    <div class="mb-2">
                        <label class="small">Receipt Date</label>
                        <input type="date" name="receipt_date" id="edit_receipt_date" class="form-control form-control-sm" required>
                    </div>

                    <div class="mb-2">
                        <label class="small">Amount</label>
                        <input type="number" step="0.01" min="0" name="amount" id="edit_amount" class="form-control form-control-sm" required>
                    </div>

                    <div class="mb-2">
                        <label class="small">Pay Mode</label>
                        <select name="pay_mode" id="edit_pay_mode" class="form-select form-select-sm">
                            <option value="">Select</option>
                            <option value="Cash">Cash</option>
                            <option value="Bank">Bank</option>
                            <option value="Cheque">Cheque</option>
                        </select>
                    </div>

                    <div class="mb-2">
                        <label class="small">Cash / Bank Account</label>
                        <select name="cash_account_id" id="edit_cash_account_id" class="form-select form-select-sm">
                            <option value="0">Select Account</option>
                            <?php mysqli_data_seek($cashAccounts, 0); ?>
                            <?php while($acc = mysqli_fetch_assoc($cashAccounts)): ?>
                                <option value="<?= (int)$acc['id'] ?>">
                                    <?= e($acc['account_name']) ?> (<?= e($acc['account_type']) ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>

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

                <div class="modal-footer">
                    <button type="submit" name="update_receipt" class="btn btn-success btn-sm">Update Receipt</button>
                    <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button>
                </div>
            </form>
        </div>
    </div>
</div>
<div class="modal fade" id="editModal">
<div class="modal-dialog">
<div class="modal-content">

<form method="post">

<div class="modal-header bg-primary text-white">
<h6>Edit Installment</h6>
<button class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
</div>

<div class="modal-body">

<input type="hidden" name="id" id="eid">

<label>Date</label>
<input type="date" name="date" id="edate" class="form-control mb-2">

<label>Amount</label>
<input type="number" name="amount" id="eamt" class="form-control mb-2">

<label>Description</label>
<input type="text" name="description" id="edesc" class="form-control">

</div>

<div class="modal-footer">
<button name="update_installment" class="btn btn-success btn-sm">Update</button>
</div>

</form>

</div>
</div>
</div>

<script>
function editInstallment(id,date,amt,desc){
    document.getElementById('eid').value=id;
    document.getElementById('edate').value=date;
    document.getElementById('eamt').value=amt;
    document.getElementById('edesc').value=desc;

    new bootstrap.Modal(document.getElementById('editModal')).show();
}
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
function openEditModal(id, receiptDate, amount, payMode, cashAccountId, remarks){
    document.getElementById('edit_receipt_id').value = id;
    document.getElementById('edit_receipt_date').value = receiptDate;
    document.getElementById('edit_amount').value = amount;
    document.getElementById('edit_pay_mode').value = payMode;
    document.getElementById('edit_cash_account_id').value = cashAccountId;
    document.getElementById('edit_remarks').value = remarks;

    var modal = new bootstrap.Modal(document.getElementById('editReceiptModal'));
    modal.show();
}
</script>

</body>
</html>