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

session_start();
require "db.php";

/* -----------------------------
   VALIDATION (FIRST!)
------------------------------*/
if (!isset($_SESSION['hps_sale_id'])) {
    header("Location: hps_sale_customer.php");
    exit;
}

$sale_id = (int)$_SESSION['hps_sale_id'];
if ($sale_id <= 0) die("Invalid Sale");

/* -----------------------------
   LOAD OR CREATE CHECKLIST
------------------------------*/
$res = mysqli_query($conn, "
    SELECT * FROM hps_checklist WHERE sale_id=$sale_id LIMIT 1
");
$checklist = mysqli_fetch_assoc($res);

if (!$checklist) {
    mysqli_query($conn, "
        INSERT INTO hps_checklist (sale_id)
        VALUES ($sale_id)
    ");
    $res = mysqli_query($conn, "
        SELECT * FROM hps_checklist WHERE sale_id=$sale_id LIMIT 1
    ");
    $checklist = mysqli_fetch_assoc($res);
}

/* -----------------------------
   NORMALIZE VALUES
------------------------------*/
for ($i = 1; $i <= 8; $i++) {
    if (!isset($checklist["item$i"]) || $checklist["item$i"] === null) {
        $checklist["item$i"] = 0;
    }
}
$checklist['remarks'] = $checklist['remarks'] ?? '';

/* -----------------------------
   SAVE CHECKLIST
------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $set = [];
    for ($i = 1; $i <= 8; $i++) {
        $set[] = "item$i=" . (isset($_POST["item$i"]) ? 1 : 0);
    }

    $remarks = mysqli_real_escape_string($conn, $_POST['remarks'] ?? '');
    $set[] = "remarks='$remarks'";

    mysqli_query($conn, "
        UPDATE hps_checklist SET
        " . implode(',', $set) . "
        WHERE sale_id=$sale_id
    ");

    /* -------- FILE UPLOAD -------- */
    if (!empty($_FILES['docs']['name'][0])) {
        $dir = "uploads/hps_docs/$sale_id/";
        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }

        foreach ($_FILES['docs']['tmp_name'] as $k => $tmp) {
            if ($tmp == '') continue;
            $name = time() . '_' . basename($_FILES['docs']['name'][$k]);
            move_uploaded_file($tmp, $dir . $name);
        }
    }

    /* -------- SUBMIT FOR APPROVAL (NO BLOCKING) -------- */
    if (isset($_POST['submit_approval'])) {

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

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

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

/* -----------------------------
   DOCUMENT LABELS
------------------------------*/
$docs = [
    1 => "Customer CNIC Copy",
    2 => "Customer Photograph",
    3 => "Guarantor CNIC Copy",
    4 => "Guarantor Photograph",
    5 => "Signed Agreement",
    6 => "Cheque Copy",
    7 => "Utility Bill",
    8 => "Verification Form"
];
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Step 4 — Documents Checklist</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container py-3">

<h4 class="mb-3">Step 4 — Documents Checklist</h4>

<div class="progress mb-3">
  <div class="progress-bar" style="width:55%">Step 4 of 7</div>
</div>

<form method="post" enctype="multipart/form-data">

<div class="row">
<?php for ($i=1;$i<=8;$i++): ?>
<div class="col-md-4 mb-2">
<label class="form-check">
<input type="checkbox"
       class="form-check-input"
       name="item<?= $i ?>"
       <?= ((int)$checklist["item$i"] === 1) ? 'checked' : '' ?>>
<?= $docs[$i] ?>
</label>
</div>
<?php endfor; ?>
</div>

<div class="mt-3">
<label class="small">Upload Documents</label>
<input type="file" name="docs[]" multiple class="form-control form-control-sm">
</div>

<div class="mt-3">
<label class="small">Remarks</label>
<textarea name="remarks" class="form-control form-control-sm" rows="2"><?= htmlspecialchars($checklist['remarks']) ?></textarea>
</div>

<hr>

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

<button name="submit_approval"
        class="btn btn-primary btn-sm float-end"
        onclick="return confirm('Submit sale for approval?');">
Submit for Approval →
</button>

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