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

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

$sale_id = (int)$_SESSION['hps_sale_id'];


/* =============================
   SAVE DOCUMENTATION + SALESPERSON + SALE REF
============================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_doc'])) {

    $doc = (float)($_POST['documentation_charges'] ?? 0);
    $salesperson_id = (int)($_POST['salesperson_id'] ?? 0);
    $sale_ref = mysqli_real_escape_string($conn, $_POST['sale_ref'] ?? '');

    mysqli_query($conn, "
        UPDATE hps_sales
        SET documentation_charges = $doc,
            salesperson_id = $salesperson_id,
            sale_ref = '$sale_ref'
        WHERE id = $sale_id
    ");

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

/* =============================
   ADD PRODUCT TO SALE
============================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_item'])) {

    $product_id   = (int)($_POST['product_id'] ?? 0);
    $qty          = max(1, (int)($_POST['qty'] ?? 1));
    $price        = (float)($_POST['price'] ?? 0);
    $down_payment = (float)($_POST['down_payment'] ?? 0);
    $installments = max(1, (int)($_POST['installments'] ?? 1));
    $markup_percent = (float)($_POST['markup'] ?? 0);

    if ($product_id <= 0 || $price <= 0) {
        header("Location: hps_sale_products.php");
        exit;
    }

    /* ===== HP CALCULATION ===== */

    $base_amount = $price * $qty;

    $finance_amount = $base_amount - $down_payment;
    if ($finance_amount < 0) $finance_amount = 0;

    $applicable_markup_rate = $markup_percent * ($installments / 12);
    $markup_amount = ($applicable_markup_rate / 100) * $finance_amount;

    $hp_amount = $finance_amount + $markup_amount;

    $monthly = 0;
    if ($installments > 0) {
        $monthly = round($hp_amount / $installments, 0);
    }

    mysqli_query($conn, "
        INSERT INTO hps_sale_items
        (sale_id, product_id, qty, price, down_payment, installments, markup_rate, monthly_installment)
        VALUES
        ($sale_id, $product_id, $qty, $price, $down_payment, $installments, $markup_percent, $monthly)
    ");

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

/* =============================
   REMOVE ITEM
============================= */
if (isset($_GET['del'])) {
    $id = (int)$_GET['del'];
    mysqli_query($conn, "DELETE FROM hps_sale_items WHERE id=$id AND sale_id=$sale_id");
    header("Location: hps_sale_products.php");
    exit;
}

/* =============================
   FETCH PRODUCTS
============================= */
$products = mysqli_query($conn, "
    SELECT * FROM hps_products 
    ORDER BY name
");

/* =============================
   FETCH SALE ITEMS
============================= */
$items = mysqli_query($conn, "
    SELECT i.*, p.name
    FROM hps_sale_items i
    JOIN hps_products p ON p.id=i.product_id
    WHERE i.sale_id=$sale_id
");

/* =============================
   FETCH SALE HEADER
============================= */
$sale = mysqli_fetch_assoc(mysqli_query($conn, "
    SELECT documentation_charges, salesperson_id
    FROM hps_sales
    WHERE id=$sale_id
    LIMIT 1
"));

$doc_charges = (float)($sale['documentation_charges'] ?? 0);
$current_sp_id = (int)($sale['salesperson_id'] ?? 0);

/* =============================
   FETCH SALESPERSONS
============================= */
$salespersons = mysqli_query($conn, "
    SELECT id, name
    FROM hps_salespersons
    WHERE status='Active'
    ORDER BY name
");
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Step 2 — Products</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>

<div class="container py-3">

<h4 class="mb-3">Step 2 — Add Products</h4>

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

<!-- DOCUMENTATION + SALESPERSON -->
<form method="post" class="row g-2 mb-3">

  <div class="col-md-4">
    <label class="form-label small">Documentation Charges</label>
    <input type="number" step="0.01"
           name="documentation_charges"
           value="<?= htmlspecialchars($doc_charges) ?>"
           class="form-control form-control-sm">
  </div>

  <div class="col-md-4">
    <label class="form-label small">Salesperson</label>
    <select name="salesperson_id" class="form-select form-select-sm" required>
        <option value="">Select Salesperson</option>
        <?php while($sp = mysqli_fetch_assoc($salespersons)) { ?>
            <option value="<?= $sp['id'] ?>"
                <?= ($sp['id'] == $current_sp_id) ? 'selected' : '' ?>>
                <?= htmlspecialchars($sp['name']) ?>
            </option>
        <?php } ?>
    </select>
  </div>
  <div class="form-group">
    <label>Sale Ref (Manual)</label>
    <input type="text" name="sale_ref" class="form-control">
</div>



  <div class="col-md-2 d-flex align-items-end">
    <button name="save_doc" class="btn btn-secondary btn-sm w-100">
      Save
    </button>
  </div>

</form>

<!-- ADD PRODUCT -->
<form method="post" class="row g-2 mb-4">

  <div class="col-md-3">
    <label class="form-label small">Product</label>
    <select name="product_id" class="form-select form-select-sm" required>
      <option value="">Select</option>
      <?php while($p=mysqli_fetch_assoc($products)): ?>
        <option value="<?= $p['id'] ?>" data-price="<?= $p['price'] ?>">
          <?= htmlspecialchars($p['name']) ?> (<?= $p['price'] ?>)
        </option>
      <?php endwhile; ?>
    </select>
  </div>

  <div class="col-md-1">
    <label class="form-label small">Qty</label>
    <input type="number" name="qty" value="1" class="form-control form-control-sm" min="1">
  </div>

  <div class="col-md-2">
    <label class="form-label small">Price</label>
    <input type="number" name="price" class="form-control form-control-sm" step="0.01" min="0">
  </div>

  <div class="col-md-2">
    <label class="form-label small">Down Payment</label>
    <input type="number" name="down_payment" value="0" class="form-control form-control-sm" step="0.01" min="0">
  </div>

  <div class="col-md-1">
    <label class="form-label small">Inst.</label>
    <input type="number" name="installments" value="12" class="form-control form-control-sm" min="1">
  </div>

  <div class="col-md-1">
    <label class="form-label small">Markup % (Annual)</label>
    <input type="number" name="markup" value="0" class="form-control form-control-sm" step="0.01" min="0">
  </div>

  <div class="col-md-2 d-flex align-items-end">
    <button name="add_item" class="btn btn-primary btn-sm w-100">Add</button>
  </div>

</form>

<!-- ITEMS -->
<table class="table table-bordered table-sm">
<thead class="table-dark">
<tr>
  <th>Product</th>
  <th>Qty</th>
  <th>Price</th>
  <th>Base</th>
  <th>Down</th>
  <th>Doc</th>
  <th>Initial Pay</th>
  <th>Inst</th>
  <th>Markup %</th>
  <th>Monthly</th>
  <th width="60">X</th>
</tr>
</thead>
<tbody>
<?php while($r=mysqli_fetch_assoc($items)): ?>
<?php
    $qty   = (int)$r['qty'];
    $price = (float)$r['price'];
    $down  = (float)$r['down_payment'];
    $inst  = max(1, (int)$r['installments']);
    $mperc = (float)$r['markup_rate']; // annual percent saved

    $base_amount = $price * $qty;
    $finance_amount = $base_amount - $down;
    if ($finance_amount < 0) $finance_amount = 0;

    $markup_rate = $mperc / 100;
    $applicable_markup_rate = $markup_rate * ($inst / 12);
    $markup_amount = $applicable_markup_rate * $finance_amount;
    $hp_amount = $finance_amount + $markup_amount;

    $initial_payment = $down + $doc_charges;
?>
<tr>
  <td><?= htmlspecialchars($r['name']) ?></td>
  <td><?= $qty ?></td>
  <td><?= number_format($price, 2) ?></td>
  <td><?= number_format($base_amount, 2) ?></td>
  <td><?= number_format($down, 2) ?></td>
  <td><?= number_format($doc_charges, 2) ?></td>
  <td><?= number_format($initial_payment, 2) ?></td>
  <td><?= $inst ?></td>
  <td><?= number_format($mperc, 2) ?></td>
  <td><?= number_format((float)$r['monthly_installment'], 0)?></td>
  <td>
    <a href="?del=<?= $r['id'] ?>" class="btn btn-danger btn-sm">X</a>
  </td>
</tr>
<?php endwhile; ?>

<?php
$total_qty = 0;
$total_base = 0;
$total_down = 0;
$total_doc = 0;
$total_initial = 0;
$total_monthly = 0;

mysqli_data_seek($items, 0);
while ($r = mysqli_fetch_assoc($items)) {

    $base = $r['qty'] * $r['price'];

    $total_qty     += $r['qty'];
    $total_base    += $base;
    $total_down    += $r['down_payment'];
    $total_doc     += $doc_charges;
    $total_initial += ($r['down_payment'] + $doc_charges);
    $total_monthly += $r['monthly_installment'];
}
?>

</tbody>
<tfoot class="table-secondary fw-bold">
<tr>
  <td>Total</td>
  <td><?= $total_qty ?></td>
  <td></td>
  <td><?= number_format($total_base,2) ?></td>
  <td><?= number_format($total_down,2) ?></td>
  <td><?= number_format($total_doc,2) ?></td>
  <td><?= number_format($total_initial,2) ?></td>
  <td></td>
  <td></td>
  <td><?= number_format($total_monthly,0) ?></td>
  <td></td>
</tr>
</tfoot>

</table>

<div class="text-end mt-3">
  <a href="hps_sale_schedule.php" class="btn btn-success btn-sm">
    Save & Next →
  </a>
</div>

</div>

<script>
document.querySelector('select[name="product_id"]').addEventListener('change', function(){
    let price = this.options[this.selectedIndex].dataset.price;
    document.querySelector('input[name="price"]').value = price || '';
});
</script>

</body>
</html>
