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

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
function n0($v){ return is_numeric($v) ? (float)$v : 0; }

if (!isset($_SESSION['purchase_cart'])) $_SESSION['purchase_cart'] = [];
if (!isset($_SESSION['purchase_hdr']))  $_SESSION['purchase_hdr']  = [
    'supplier_id' => 0,
    'invoice_no'  => '',
    'invoice_date'=> date('Y-m-d'),
    'remarks'     => ''
];

$cart = &$_SESSION['purchase_cart'];
$hdr  = &$_SESSION['purchase_hdr'];

$alert = "";

/* -----------------------------
   LOAD SUPPLIERS + PRODUCTS
------------------------------*/
$supRes = mysqli_query($conn, "SELECT id, name, mobile FROM hps_suppliers ORDER BY name");
$prodRes = mysqli_query($conn, "SELECT id, name, price, avg_cost FROM hps_products ORDER BY name");

/* -----------------------------
   SET HEADER (supplier/invoice)
------------------------------*/
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['set_header'])) {
    $hdr['supplier_id']  = (int)($_POST['supplier_id'] ?? 0);
    $hdr['invoice_no']   = trim($_POST['invoice_no'] ?? '');
    $hdr['invoice_date'] = $_POST['invoice_date'] ?? date('Y-m-d');
    $hdr['remarks']      = trim($_POST['remarks'] ?? '');

    if ($hdr['supplier_id'] <= 0 || $hdr['invoice_no'] === '') {
        $alert = "Please select supplier and enter invoice number.";
    } else {
        $alert = "Invoice header saved. Now add items.";
    }
}

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

    if ((int)$hdr['supplier_id'] <= 0 || $hdr['invoice_no']==='') {
        $alert = "Please set supplier + invoice info first.";
    } else {
        $product_id = (int)($_POST['product_id'] ?? 0);
        $qty  = n0($_POST['qty'] ?? 0);
        $cost = n0($_POST['cost'] ?? 0);

        if ($product_id<=0 || $qty<=0 || $cost<=0) {
            $alert = "Please select product and enter qty + cost.";
        } else {
            // If same product already in cart, add qty and overwrite cost with latest entered
            if (!isset($cart[$product_id])) {
                $cart[$product_id] = ['qty'=>0,'cost'=>0];
            }
            $cart[$product_id]['qty'] += $qty;
            $cart[$product_id]['cost'] = $cost;

            $alert = "Item added.";
        }
    }
}

/* -----------------------------
   REMOVE ITEM
------------------------------*/
if (isset($_GET['remove']) && is_numeric($_GET['remove'])) {
    $pid = (int)$_GET['remove'];
    if (isset($cart[$pid])) unset($cart[$pid]);
    header("Location: hps_purchase.php");
    exit;
}

/* -----------------------------
   CANCEL INVOICE (CLEAR)
------------------------------*/
if (isset($_GET['cancel'])) {
    $_SESSION['purchase_cart'] = [];
    $_SESSION['purchase_hdr']  = ['supplier_id'=>0,'invoice_no'=>'','invoice_date'=>date('Y-m-d'),'remarks'=>''];
    header("Location: hps_purchase.php");
    exit;
}

/* -----------------------------
   SAVE INVOICE
   - inserts purchase header + items
   - updates stock qty
   - recalculates avg cost
   - updates hps_products.avg_cost also
------------------------------*/
/* -----------------------------
   SAVE INVOICE
   - inserts purchase header + items
   - updates stock qty
   - recalculates avg cost
   - updates hps_products.avg_cost also
------------------------------*/
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_invoice'])) {

    if ((int)$hdr['supplier_id'] <= 0 || $hdr['invoice_no']==='') {
        $alert = "Please set supplier + invoice info first.";
    } elseif (count($cart) == 0) {
        $alert = "No items to save.";
    } else {

        $supplier_id = (int)$hdr['supplier_id'];
        $invoice_no  = mysqli_real_escape_string($conn, $hdr['invoice_no']);
        $invoice_date= mysqli_real_escape_string($conn, $hdr['invoice_date']);
        $remarks     = mysqli_real_escape_string($conn, $hdr['remarks']);

        // Calculate grand total
        $grand = 0;
        foreach ($cart as $pid=>$it){
            $grand += ((float)$it['qty'] * (float)$it['cost']);
        }
        $grand = round($grand, 2);

        mysqli_begin_transaction($conn);

        try {

            /* =============================
               INSERT PURCHASE HEADER
            ============================== */
            $q = mysqli_query($conn,"
                INSERT INTO hps_purchases
                (supplier_id, invoice_no, invoice_date, remarks, grand_total)
                VALUES
                ($supplier_id,'$invoice_no','$invoice_date','$remarks',$grand)
            ");
            if(!$q) throw new Exception(mysqli_error($conn));

            $purchase_id = mysqli_insert_id($conn);

            /* =============================
               SUPPLIER LEDGER ENTRY
            ============================== */
            $q = mysqli_query($conn,"
                INSERT INTO hps_supplier_ledger
                (supplier_id, trans_date, description, dr, cr, ref_type, ref_id)
                VALUES
                (
                    $supplier_id,
                    '$invoice_date',
                    'Purchase Invoice #$invoice_no',
                    $grand,
                    0,
                    'Purchase',
                    $purchase_id
                )
            ");
            if(!$q) throw new Exception(mysqli_error($conn));

            /* =============================
               INSERT ITEMS + UPDATE STOCK
            ============================== */
            foreach ($cart as $product_id=>$it) {

                $product_id = (int)$product_id;
                $qty  = round((float)$it['qty'], 2);
                $cost = round((float)$it['cost'], 2);
                $line_total = round($qty * $cost, 2);

                if($qty <= 0 || $cost <= 0) continue;

                /* Insert purchase item */
                $q = mysqli_query($conn,"
                    INSERT INTO hps_purchase_items
                    (purchase_id, product_id, qty, cost, line_total)
                    VALUES
                    ($purchase_id, $product_id, $qty, $cost, $line_total)
                ");
                if(!$q) throw new Exception(mysqli_error($conn));

                /* Ensure stock row exists */
                mysqli_query($conn,"
                    INSERT INTO hps_stock (product_id, qty_on_hand, avg_cost)
                    SELECT $product_id, 0, 0
                    WHERE NOT EXISTS
                    (SELECT 1 FROM hps_stock WHERE product_id=$product_id)
                ");

                /* Lock stock row */
                $st = mysqli_fetch_assoc(mysqli_query($conn,"
                    SELECT qty_on_hand, avg_cost
                    FROM hps_stock
                    WHERE product_id=$product_id
                    FOR UPDATE
                "));

                if(!$st) throw new Exception("Stock row missing for product ID $product_id");

                $old_qty = (float)$st['qty_on_hand'];
                $old_avg = (float)$st['avg_cost'];

                $new_qty = $old_qty + $qty;

                /* Weighted Average Cost */
                if ($new_qty > 0) {
                    $new_avg = (
                        ($old_qty * $old_avg) +
                        ($qty * $cost)
                    ) / $new_qty;
                } else {
                    $new_avg = $cost;
                }

                $new_avg = round($new_avg, 2);

                /* Update stock */
                $q = mysqli_query($conn,"
                    UPDATE hps_stock
                    SET qty_on_hand = $new_qty,
                        avg_cost = $new_avg
                    WHERE product_id = $product_id
                ");
                if(!$q) throw new Exception(mysqli_error($conn));

                /* Update products table avg_cost */
                $q = mysqli_query($conn,"
                    UPDATE hps_products
                    SET avg_cost = $new_avg
                    WHERE id = $product_id
                ");
                if(!$q) throw new Exception(mysqli_error($conn));
            }

            mysqli_commit($conn);

            $_SESSION['purchase_cart'] = [];
            $_SESSION['purchase_hdr']  = [
                'supplier_id'=>0,
                'invoice_no'=>'',
                'invoice_date'=>date('Y-m-d'),
                'remarks'=>''
            ];

            header("Location: hps_purchase.php?ok=1&pid=".$purchase_id);
            exit;

        } catch (Exception $e) {

            mysqli_rollback($conn);
            $alert = "Save failed: " . $e->getMessage();
        }
    }
}


/* -----------------------------
   Fetch cart items with names
------------------------------*/
$cartRows = [];
$grandTotal = 0;

if (count($cart)) {
    $ids = implode(',', array_map('intval', array_keys($cart)));
    $r = mysqli_query($conn, "SELECT id, name FROM hps_products WHERE id IN ($ids)");
    $names = [];
    while($x=mysqli_fetch_assoc($r)) $names[(int)$x['id']] = $x['name'];

    foreach ($cart as $pid=>$it) {
        $qty  = (float)$it['qty'];
        $cost = (float)$it['cost'];
        $lt = $qty*$cost;
        $grandTotal += $lt;

        $cartRows[] = [
            'product_id' => (int)$pid,
            'product' => $names[(int)$pid] ?? ('#'.$pid),
            'qty' => $qty,
            'cost'=> $cost,
            'total'=> $lt
        ];
    }
    $grandTotal = round($grandTotal,2);
}

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Purchase Invoice</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:rgba(200,200,200,.70);
  border-radius:30px;
  padding:24px;
  margin:30px auto;
  max-width:1200px;
  box-shadow:0 10px 25px rgba(0,0,0,.08), 0 2px 6px rgba(0,0,0,.06);
}
.form-control,.form-select{border:1.5px solid #6c757d}
.table tbody tr:hover{background:#eaf5ea; cursor:pointer}
</style>
</head>
<body>

<div class="container-fluid">
  <div class="main-card">

    <div class="d-flex justify-content-between align-items-center mb-2">
      <h4 class="mb-0">Purchase Invoice</h4>
      <a href="?cancel=1" class="btn btn-outline-danger btn-sm">Cancel Draft</a>
    </div>

    <?php if(isset($_GET['ok'])): ?>
      <div class="alert alert-success py-2">
        ✅ Purchase saved. Purchase ID: <b><?=esc($_GET['pid'] ?? '')?></b>
      </div>
    <?php endif; ?>

    <?php if($alert): ?>
      <div class="alert alert-warning py-2"><?=esc($alert)?></div>
    <?php endif; ?>

    <!-- HEADER -->
    <div class="card mb-3">
      <div class="card-header fw-bold">Invoice Info</div>
      <div class="card-body">
        <form method="post" class="row g-2">
          <input type="hidden" name="set_header" value="1">

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

          <div class="col-md-3">
            <label class="small">Invoice No</label>
            <input class="form-control form-control-sm" name="invoice_no" value="<?=esc($hdr['invoice_no'])?>" required>
          </div>

          <div class="col-md-3">
            <label class="small">Invoice Date</label>
            <input type="date" class="form-control form-control-sm" name="invoice_date" value="<?=esc($hdr['invoice_date'])?>">
          </div>

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

          <div class="col-md-12">
            <label class="small">Remarks</label>
            <input class="form-control form-control-sm" name="remarks" value="<?=esc($hdr['remarks'])?>">
          </div>
        </form>
      </div>
    </div>

    <!-- ADD ITEM -->
    <div class="card mb-3">
      <div class="card-header fw-bold">Add Items</div>
      <div class="card-body">
        <form method="post" class="row g-2">
          <input type="hidden" name="add_item" value="1">

          <div class="col-md-6">
            <label class="small">Product (search)</label>
            <select class="form-select form-select-sm" name="product_id" required>
              <option value="">Select product</option>
              <?php while($p=mysqli_fetch_assoc($prodRes)): ?>
                <option value="<?=$p['id']?>">
                  <?=esc($p['name'])?> — AvgCost: <?=number_format((float)$p['avg_cost'],2)?>
                </option>
              <?php endwhile; ?>
            </select>
          </div>

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

          <div class="col-md-2">
            <label class="small">Cost</label>
            <input type="number" step="0.01" class="form-control form-control-sm" name="cost" required>
          </div>

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

        </form>
      </div>
    </div>

    <!-- CART TABLE -->
    <div class="card mb-2">
      <div class="card-header fw-bold d-flex justify-content-between">
        <span>Invoice Items</span>
        <span>Grand Total: <b><?=number_format($grandTotal,2)?></b></span>
      </div>
      <div class="card-body">

        <table class="table table-bordered table-sm">
          <thead class="table-dark">
            <tr>
              <th>#</th>
              <th>Product</th>
              <th class="text-end">Qty</th>
              <th class="text-end">Cost</th>
              <th class="text-end">Line Total</th>
              <th width="60">X</th>
            </tr>
          </thead>
          <tbody>
            <?php if(!count($cartRows)): ?>
              <tr><td colspan="6" class="text-center text-muted">No items added</td></tr>
            <?php else: ?>
              <?php $i=1; foreach($cartRows as $r): ?>
                <tr>
                  <td><?=$i++?></td>
                  <td><?=esc($r['product'])?></td>
                  <td class="text-end"><?=number_format($r['qty'],2)?></td>
                  <td class="text-end"><?=number_format($r['cost'],2)?></td>
                  <td class="text-end"><?=number_format($r['total'],2)?></td>
                  <td class="text-center">
                    <a class="btn btn-danger btn-sm" href="?remove=<?=$r['product_id']?>">X</a>
                  </td>
                </tr>
              <?php endforeach; ?>
            <?php endif; ?>
          </tbody>
        </table>

        <form method="post" class="text-end">
          <button name="save_invoice" class="btn btn-primary"
            <?= (count($cartRows)==0 || (int)$hdr['supplier_id']<=0 || $hdr['invoice_no']==='') ? 'disabled' : '' ?>>
            SAVE Invoice
          </button>
        </form>

      </div>
    </div>

  </div>
</div>

</body>
</html>
