<?php
// hps_supplier_payment.php
require "db.php";

/* -----------------------------
   HELPERS
------------------------------*/
function esc($v){
    return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8');
}

/* -----------------------------
   FETCH SUPPLIERS
------------------------------*/
$suppliers = mysqli_query($conn,"
    SELECT id, name
    FROM hps_suppliers
    ORDER BY name
");

/* -----------------------------
   HANDLE PAYMENT SAVE
------------------------------*/
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_payment'])) {

    $supplier_id = (int)$_POST['supplier_id'];
    $date        = $_POST['pay_date'];
    $amount      = (float)$_POST['amount'];
    $mode        = mysqli_real_escape_string($conn,$_POST['pay_mode']);
    $remarks     = mysqli_real_escape_string($conn,$_POST['remarks']);

    if ($supplier_id > 0 && $amount > 0) {

        /* ===== SUPPLIER LEDGER ENTRY (UNCHANGED CORE LOGIC) ===== */
        mysqli_query($conn,"
            INSERT INTO hps_supplier_ledger
            (supplier_id, trans_date, description, dr, cr, ref_type)
            VALUES
            (
                $supplier_id,
                '$date',
                'Supplier Payment',
                0,
                $amount,
                'Payment'
            )
        ");

        /* =====================================================
           PETTY CASH INTEGRATION (CASH PAYMENTS ONLY)
           -----------------------------------------------------
           Description: Supplier Payment (Supplier Name)
        ====================================================== */
        if ($mode === 'Cash') {

            /* get petty cash (staff) account */
            $staffAcc = mysqli_fetch_assoc(mysqli_query($conn,"
                SELECT id
                FROM hps_cash_accounts
                WHERE account_type='STAFF'
                ORDER BY id
                LIMIT 1
            "));

            if ($staffAcc) {
                $staff_id = (int)$staffAcc['id'];

                /* get supplier name */
                $sup = mysqli_fetch_assoc(mysqli_query($conn,"
                    SELECT name
                    FROM hps_suppliers
                    WHERE id = $supplier_id
                    LIMIT 1
                "));

                $desc = 'SUPPLIER PAYMENT';
                if ($sup) {
                    $desc = mysqli_real_escape_string(
                        $conn,
                        'Supplier Payment ('.$sup['name'].')'
                    );
                }

                mysqli_query($conn,"
                    INSERT INTO hps_cashbook
                    (trans_date, description, from_account, to_account, amount, ref_type)
                    VALUES
                    (
                        '$date',
                        '$desc',
                        $staff_id,
                        NULL,
                        $amount,
                        'PETTY_SUPPLIER_PAYMENT'
                    )
                ");
            }
        }
        /* ================= END PETTY CASH =================== */

        header("Location: hps_supplier_payment.php?ok=1");
        exit;
    }
}

/* -----------------------------
   SUPPLIER BALANCES
------------------------------*/
$balances = [];
$balQ = mysqli_query($conn,"
    SELECT supplier_id,
           SUM(dr - cr) AS balance
    FROM hps_supplier_ledger
    GROUP BY supplier_id
");
while($b=mysqli_fetch_assoc($balQ)){
    $balances[$b['supplier_id']] = $b['balance'];
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Supplier Payment</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body{background:#f1f3f5}
.main-card{
    background:#fff;
    max-width:900px;
    margin:30px auto;
    padding:25px;
    border-radius:20px;
    box-shadow:0 10px 25px rgba(0,0,0,.1);
}
.form-control:focus{
    border-color:#198754;
    box-shadow:0 0 0 .15rem rgba(25,135,84,.25);
}
</style>
</head>
<body>

<div class="main-card">

<h4 class="mb-3">Supplier Payment</h4>

<?php if(isset($_GET['ok'])): ?>
<div class="alert alert-success py-2">✅ Payment saved successfully</div>
<?php endif; ?>

<form method="post" class="row g-3">

<div class="col-md-6">
<label class="small">Supplier</label>
<select name="supplier_id" class="form-select form-select-sm" required>
<option value="">Select supplier</option>
<?php while($s=mysqli_fetch_assoc($suppliers)): ?>
<option value="<?=$s['id']?>"><?=esc($s['name'])?></option>
<?php endwhile; ?>
</select>
</div>

<div class="col-md-6">
<label class="small">Payment Date</label>
<input type="date" name="pay_date"
value="<?=date('Y-m-d')?>"
class="form-control form-control-sm" required>
</div>

<div class="col-md-4">
<label class="small">Amount</label>
<input type="number" step="0.01" name="amount"
class="form-control form-control-sm" required>
</div>

<div class="col-md-4">
<label class="small">Payment Mode</label>
<select name="pay_mode" class="form-select form-select-sm" required>
<option>Cash</option>
<option>Bank</option>
<option>Cheque</option>
</select>
</div>

<div class="col-md-4">
<label class="small">Remarks</label>
<input type="text" name="remarks"
class="form-control form-control-sm"
placeholder="Optional remarks">
</div>

<div class="col-12 text-end">
<button name="save_payment" class="btn btn-success btn-sm">
Save Payment
</button>
</div>

</form>

<hr>

<h6 class="mt-4">Supplier Outstanding Summary</h6>

<table class="table table-sm table-bordered">
<thead class="table-dark">
<tr>
<th>Supplier</th>
<th class="text-end">Outstanding</th>
</tr>
</thead>
<tbody>
<?php
$res = mysqli_query($conn,"SELECT id, name FROM hps_suppliers");
while($r=mysqli_fetch_assoc($res)):
$bal = $balances[$r['id']] ?? 0;
?>
<tr>
<td><?=esc($r['name'])?></td>
<td class="text-end <?= $bal>0?'text-danger':'text-success' ?>">
<?=number_format($bal,2)?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>

</body>
</html>
