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

session_start();
require "db.php";

function e($v){
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}

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

/* ===============================
   LOAD SALE MASTER
================================ */
$sale = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT *
    FROM hps_sales
    WHERE id = $sale_id
    LIMIT 1
"));
if (!$sale) die("Sale not found");

if ($sale['status'] !== 'Pending') {
    die("Only PENDING sales can be approved");
}

/* ===============================
   LOAD SALESPERSON
================================ */
$sale_info = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT 
        s.salesperson_id,s. sale_ref,
        sp.name AS salesperson
    FROM hps_sales s
    LEFT JOIN hps_salespersons sp ON sp.id = s.salesperson_id
    WHERE s.id = $sale_id
    LIMIT 1
"));
$salesperson_name = $sale_info['salesperson'] ?? 'N/A';
$sale_ref = $sale_info['sale_ref'] ?? 'N/A';

/* ===============================
   LOAD SALE ITEMS (FOR CALC + STOCK)
   Include product_id + product name
================================ */
$items_q = mysqli_query($conn,"
    SELECT 
        si.product_id,
        p.name AS product_name,
        si.qty, si.price, si.down_payment, si.installments, si.markup_rate
    FROM hps_sale_items si
    JOIN hps_products p ON p.id = si.product_id
    WHERE si.sale_id = $sale_id
");
if(!$items_q) die("SQL ERROR: ".mysqli_error($conn));

/* ===============================
   CALCULATIONS (your existing logic)
================================ */
$cash_price     = 0;
$down_payment   = 0;
$total_markup   = 0;

$items = [];
while ($row = mysqli_fetch_assoc($items_q)) {

    $items[] = $row;

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

    $installments = (int)($row['installments'] ?? 0);
    $markup_rate  = (float)($row['markup_rate'] ?? 0);

    // markup_rate stored as percentage (20, 36 etc)
    $item_markup = $financed
        * ($markup_rate / 100)
        * ($installments / 12);

    $cash_price   += $item_price;
    $down_payment += $item_down;
    $total_markup += $item_markup;
}

/* ---- Documentation Charges ---- */
$doc = (float)$sale['documentation_charges'];

/* ===============================
   FINAL TOTALS
================================ */
$financed_total    = $cash_price - $down_payment;
$markup            = round($total_markup);
$hp_sale           = $cash_price + $markup;
$total_receivable  = $hp_sale + $doc;
$receive_now       = $down_payment + $doc;

/* ===============================
   APPROVE / REJECT
================================ */
$error = "";

/* ---------- APPROVE ---------- */
if (isset($_POST['approve'])) {

    if (($_POST['password'] ?? '') !== '1234') {
        $error = "Invalid approval password";
    } else {

        if (count($items) <= 0) {
            $error = "No sale items found. Cannot approve.";
        } else {

            // Transaction start
            mysqli_begin_transaction($conn);

            try {

                // 1) Check stock availability (lock rows)
                $stock_errors = [];

                foreach($items as $it){

                    $pid = (int)$it['product_id'];
                    $qty = (float)$it['qty'];

                    $st = mysqli_fetch_assoc(mysqli_query($conn,"
                        SELECT qty_on_hand
                        FROM hps_stock
                        WHERE product_id = $pid
                        FOR UPDATE
                    "));

                    $onhand = (float)($st['qty_on_hand'] ?? 0);

                    if ($onhand < $qty) {
                        $stock_errors[] = $it['product_name'] . " (Stock: " . number_format($onhand,2) . ", Need: " . number_format($qty,2) . ")";
                    }
                }

                if (!empty($stock_errors)) {
                    // rollback and show message
                    mysqli_rollback($conn);
                    $error = "Stock not sufficient for:<br> - " . implode("<br> - ", array_map('e',$stock_errors));
                } else {

                    // 2) Deduct stock
                    foreach($items as $it){

                        $pid = (int)$it['product_id'];
                        $qty = (float)$it['qty'];

                        $up = mysqli_query($conn,"
                            UPDATE hps_stock
                            SET qty_on_hand = qty_on_hand - $qty
                            WHERE product_id = $pid
                        ");

                        if(!$up){
                            throw new Exception("Stock update failed: " . mysqli_error($conn));
                        }
                    }

                    // 3) Mark sale approved
                    $ok = mysqli_query($conn,"
                        UPDATE hps_sales
                        SET status='Approved'
                        WHERE id=$sale_id
                    ");
                    if(!$ok){
                        throw new Exception("Sale approval failed: " . mysqli_error($conn));
                    }

                    // Commit
                    mysqli_commit($conn);

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

            } catch (Exception $ex) {
                mysqli_rollback($conn);
                $error = "Approval failed: " . e($ex->getMessage());
            }
        }
    }
}

/* ---------- REJECT ---------- */
if (isset($_POST['reject'])) {
    $reason = trim($_POST['reject_reason'] ?? '');
    if (($_POST['password'] ?? '') !== '1234') {
        $error = "Invalid approval password";
    } elseif ($reason === '') {
        $error = "Reject reason is required";
    } else {
        $reason = mysqli_real_escape_string($conn, $reason);
        mysqli_query($conn,"
            UPDATE hps_sales
            SET status='Rejected',
                remarks='$reason'
            WHERE id=$sale_id
        ");
        header("Location: hps_sale_pending.php");
        exit;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sale Approval</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>Sale Approval</h4>
<a href="hps_sale_pending.php">Back</a>

<?php if ($error): ?>
<div class="alert alert-danger mt-3"><?= $error ?></div>
<?php endif; ?>

<table class="table table-bordered table-sm mt-3" style="max-width:650px;">

<tr class="table-info">
    <th>Sales Ref:</th>
    <td><b><?= e($sale_ref) ?></b></td>
</tr>
<tr class="table-info">
    <th>Salesperson</th>
    <td><b><?= e($salesperson_name) ?></b></td>
</tr>

<tr>
    <th>Cash Price</th>
    <td><?= number_format($cash_price) ?></td>
</tr>

<tr>
    <th>Down Payment</th>
    <td><?= number_format($down_payment) ?></td>
</tr>

<tr>
    <th>Financed Amount</th>
    <td><?= number_format($financed_total) ?></td>
</tr>

<tr>
    <th>Total Markup</th>
    <td><?= number_format($markup) ?></td>
</tr>

<tr class="table-light">
    <th>HP Sale Amount</th>
    <td><b><?= number_format($hp_sale) ?></b></td>
</tr>

<tr>
    <th>Documentation Charges</th>
    <td><?= number_format($doc) ?></td>
</tr>

<tr class="table-light">
    <th>Total Receivable</th>
    <td><b><?= number_format($total_receivable) ?></b></td>
</tr>

<tr class="table-warning">
    <th>Amount to Receive Now</th>
    <td><b><?= number_format($receive_now) ?></b></td>
</tr>

</table>

<!-- ITEMS PREVIEW (optional but helpful) -->
<div class="card mb-3" style="max-width:650px;">
  <div class="card-header py-2"><b>Sale Items</b></div>
  <div class="card-body p-2">
    <table class="table table-sm table-bordered mb-0">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>Product</th>
          <th class="text-end">Qty</th>
          <th class="text-end">Price</th>
        </tr>
      </thead>
      <tbody>
      <?php if(count($items)>0): $k=1; foreach($items as $it): ?>
        <tr>
          <td><?= $k++ ?></td>
          <td><?= e($it['product_name']) ?></td>
          <td class="text-end"><?= number_format((float)$it['qty'],2) ?></td>
          <td class="text-end"><?= number_format((float)$it['price'],2) ?></td>
        </tr>
      <?php endforeach; else: ?>
        <tr><td colspan="4" class="text-center text-muted">No items</td></tr>
      <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<form method="post" class="mt-3" style="max-width:650px;">
    <div class="mb-2">
        <label class="form-label">Approval Password</label>
        <input type="password" name="password" class="form-control" required>
    </div>

    <div class="mb-2">
        <label class="form-label">Reject Reason (only if rejecting)</label>
        <input type="text" name="reject_reason" class="form-control">
    </div>

    <button name="approve" class="btn btn-success">Approve Sale</button>
    <button name="reject" class="btn btn-danger"
        onclick="return confirm('Reject this sale?');">
        Reject Sale
    </button>
</form>

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