<?php
// hps_sale_pending.php
session_start();
require "db.php";

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

/* =========================
   SAFE ESCAPE FUNCTION
========================= */
function e($v){
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

/* =========================
   CANCEL ALL PENDING SALES
========================= */
if (isset($_GET['cancel_all']) && $_GET['cancel_all'] == 1) {

    $sales = mysqli_query($conn,"
        SELECT id
        FROM hps_sales
        WHERE status='Pending'
    ");

    while ($s = mysqli_fetch_assoc($sales)) {
        $sid = (int)$s['id'];

        mysqli_query($conn,"
            UPDATE hps_sales
            SET status='Cancelled'
            WHERE id=$sid
        ");

        mysqli_query($conn,"DELETE FROM hps_sale_items WHERE sale_id=$sid");
        mysqli_query($conn,"DELETE FROM hps_checklist WHERE sale_id=$sid");
    }

    header("Location: hps_sale_pending.php");
    exit;
}

/* =========================
   CANCEL SINGLE PENDING SALE
========================= */
if (isset($_GET['cancel']) && is_numeric($_GET['cancel'])) {

    $sale_id = (int)$_GET['cancel'];

    $chk = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT status
        FROM hps_sales
        WHERE id=$sale_id
        LIMIT 1
    "));

    if ($chk && $chk['status'] === 'Pending') {

        mysqli_query($conn,"
            UPDATE hps_sales
            SET status='Cancelled'
            WHERE id=$sale_id
        ");

        mysqli_query($conn,"DELETE FROM hps_sale_items WHERE sale_id=$sale_id");
        mysqli_query($conn,"DELETE FROM hps_checklist WHERE sale_id=$sale_id");

        header("Location: hps_sale_pending.php");
        exit;
    }

    die("Sale cannot be cancelled");
}

/* =========================
   FETCH PENDING SALES
========================= */
$q = mysqli_query($conn,"
    SELECT 
        s.id, 
        s.sale_no,
        s.sale_ref, 
        s.created_at,
        c.name AS customer, 
        c.mobile,
        sp.name AS salesperson
    FROM hps_sales s
    LEFT JOIN hps_customers c 
        ON c.id = s.customer_id
    LEFT JOIN hps_salespersons sp 
        ON sp.id = s.salesperson_id
    WHERE s.status='Pending'
    ORDER BY s.id DESC
");

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Step 5 — Pending Approvals</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-radius:12px;
    padding:20px;
    box-shadow:0 3px 10px rgba(0,0,0,.08);
}
</style>

</head>
<body>

<div class="container py-3">

<div class="card-box">

<h4 class="mb-3">Step 5 — Pending Approvals</h4>

<div class="progress mb-3">
  <div class="progress-bar bg-warning" style="width:75%">
    Step 5 of 7
  </div>
</div>

<?php if ($q && mysqli_num_rows($q) > 0): ?>
<a href="hps_sale_pending.php?cancel_all=1"
   class="btn btn-danger btn-sm mb-2"
   onclick="return confirm('Cancel ALL pending sales?');">
   Cancel ALL Pending
</a>
<?php endif; ?>

<table class="table table-bordered table-sm">
<thead class="table-dark">
<tr>
    <th>#</th>
    <th>Sale Ref</th>
    <th>Customer</th>
    <th>Mobile</th>
    <th>Salesperson</th>
    <th>Date</th>
    <th width="160">Action</th>
</tr>
</thead>
<tbody>

<?php if (!$q || mysqli_num_rows($q) == 0): ?>
<tr>
  <td colspan="7" class="text-center text-muted">
    No pending approvals
  </td>
</tr>
<?php endif; ?>

<?php $i=1; while($r=mysqli_fetch_assoc($q)): ?>
<tr>
    <td><?= $i++ ?></td>

    <td>
        <b><?= e($r['sale_ref']) ?></b>
    </td>

    <td><?= e($r['customer']) ?></td>

    <td><?= e($r['mobile']) ?></td>

    <td>
        <span class="badge bg-info text-dark">
            <?= e($r['salesperson'] ?: 'N/A') ?>
        </span>
    </td>

    <td>
        <?= !empty($r['created_at']) 
            ? date('d-M-Y', strtotime($r['created_at'])) 
            : '-' ?>
    </td>

    <td class="text-nowrap">

        <a href="hps_sale_approval.php?sale_id=<?= (int)$r['id'] ?>"
           class="btn btn-primary btn-sm">
           DETAILS
        </a>

        <a href="hps_sale_pending.php?cancel=<?= (int)$r['id'] ?>"
           class="btn btn-danger btn-sm"
           onclick="return confirm('Cancel this pending sale?');">
           CANCEL
        </a>

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

</tbody>
</table>

<a href="hps_sale_checklist.php" class="btn btn-secondary btn-sm">
← Back
</a>

</div>
</div>

</body>
</html>