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

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

function e($v){
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8');
}
function qdie($conn, $res){
    if(!$res){
        die("<pre style='color:red;font-weight:bold'>MYSQL ERROR: ".htmlspecialchars(mysqli_error($conn))."</pre>");
    }
}

/* =========================
   PASSWORD GATE (BEFORE PAGE)
========================= */
/*
  ✅ Set your password here (change it)
*/
$ACCESS_PASSWORD = "12345"; // <-- CHANGE THIS

if(isset($_GET['logout'])){
    unset($_SESSION['stock_adjust_auth']);
    header("Location: hps_stock_adjust.php");
    exit;
}

if(!isset($_SESSION['stock_adjust_auth']) || $_SESSION['stock_adjust_auth'] !== true){

    $pw_err = "";

    if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['login_pass'])){
        $pass = (string)($_POST['password'] ?? '');

        if($pass === $ACCESS_PASSWORD){
            $_SESSION['stock_adjust_auth'] = true;
            header("Location: hps_stock_adjust.php");
            exit;
        }else{
            $pw_err = "Wrong password!";
        }
    }
    ?>
    <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Stock Adjustment - Login</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
        <style>
            body{background:#f2f4f7}
            .card-login{
                max-width:420px;
                margin:90px auto;
                background:#fff;
                padding:25px;
                border-radius:18px;
                box-shadow:0 10px 25px rgba(0,0,0,.12);
            }
        </style>
    </head>
    <body>
        <div class="card-login">
            <h5 class="mb-3">🔐 Stock Adjustment Access</h5>

            <?php if($pw_err!=''): ?>
                <div class="alert alert-danger py-2"><?=e($pw_err)?></div>
            <?php endif; ?>

            <form method="post">
                <label class="form-label">Enter Password</label>
                <input type="password" name="password" class="form-control" required autofocus>
                <button class="btn btn-dark w-100 mt-3" name="login_pass">Open</button>
            </form>

            <div class="text-muted small mt-3">
                Authorized users only.
            </div>
        </div>
    </body>
    </html>
    <?php
    exit;
}

/* =========================
   MAIN LOGIC
========================= */
$msg = "";
$err = "";

/* -----------------------------
   SAVE ADJUSTMENT
------------------------------*/
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_adjustment'])){

    $product_id = (int)($_POST['product_id'] ?? 0);
    $new_qty    = (float)($_POST['new_qty'] ?? 0);
    $reason_in  = trim($_POST['reason'] ?? '');
    $reason     = mysqli_real_escape_string($conn, $reason_in);
    $user       = $_SESSION['username'] ?? ($_SESSION['user_name'] ?? 'Admin');

    if($product_id <= 0){
        $err = "Invalid product.";
    }elseif($reason_in === ''){
        $err = "Reason is required.";
    }else{

        mysqli_begin_transaction($conn);

        // Ensure product exists
        $chkP = mysqli_query($conn,"SELECT id FROM hps_products WHERE id=$product_id LIMIT 1");
        qdie($conn,$chkP);
        if(mysqli_num_rows($chkP)===0){
            mysqli_rollback($conn);
            $err = "Product not found.";
        }else{

            // Lock stock row if exists
            $oldRes = mysqli_query($conn,"
                SELECT qty_on_hand
                FROM hps_stock
                WHERE product_id=$product_id
                FOR UPDATE
            ");
            qdie($conn,$oldRes);

            if(mysqli_num_rows($oldRes)===0){
                // create stock row if missing
                $ins = mysqli_query($conn,"
                    INSERT INTO hps_stock (product_id, qty_on_hand, avg_cost)
                    VALUES ($product_id, 0, 0)
                ");
                qdie($conn,$ins);

                $old_qty = 0;
            }else{
                $old = mysqli_fetch_assoc($oldRes);
                $old_qty = (float)$old['qty_on_hand'];
            }

            $difference = $new_qty - $old_qty;

            $up = mysqli_query($conn,"
                UPDATE hps_stock
                SET qty_on_hand = $new_qty
                WHERE product_id = $product_id
            ");
            qdie($conn,$up);

            // Create adjustments table automatically if missing (safety)
            mysqli_query($conn,"
                CREATE TABLE IF NOT EXISTS hps_stock_adjustments (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    product_id INT NOT NULL,
                    old_qty DECIMAL(12,2) NOT NULL,
                    new_qty DECIMAL(12,2) NOT NULL,
                    difference DECIMAL(12,2) NOT NULL,
                    reason VARCHAR(255),
                    adjusted_by VARCHAR(100),
                    adjusted_at DATETIME DEFAULT CURRENT_TIMESTAMP
                )
            ");

            $insAdj = mysqli_query($conn,"
                INSERT INTO hps_stock_adjustments
                (product_id, old_qty, new_qty, difference, reason, adjusted_by)
                VALUES
                ($product_id, $old_qty, $new_qty, $difference, '$reason', '".mysqli_real_escape_string($conn,$user)."')
            ");
            qdie($conn,$insAdj);

            mysqli_commit($conn);
            $msg = "Stock adjusted successfully!";
        }
    }
}

/* -----------------------------
   SEARCH
------------------------------*/
$search_raw = $_GET['search'] ?? '';
$search = mysqli_real_escape_string($conn, $search_raw);

/* -----------------------------
   FETCH ALL STOCK (SAFE)
------------------------------*/
$where = "";
if($search !== ''){
    $where = " WHERE p.name LIKE '%$search%' ";
}

$sql = "
SELECT
    p.id,
    p.name,
    p.price,
    p.reorder_level,
    IFNULL(s.qty_on_hand,0) AS qty_on_hand,
    IFNULL(s.avg_cost,0)    AS avg_cost,
    (IFNULL(s.qty_on_hand,0) * IFNULL(s.avg_cost,0)) AS stock_value
FROM hps_products p
LEFT JOIN hps_stock s ON s.product_id = p.id
$where
ORDER BY p.name ASC
";

$res = mysqli_query($conn,$sql);
qdie($conn,$res);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Stock Adjustment</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body{background:#f2f4f7}
.main-card{
    background:#fff;
    border-radius:20px;
    padding:25px;
    margin:30px auto;
    max-width:1300px;
    box-shadow:0 10px 25px rgba(0,0,0,.12);
}
.table tbody tr:hover{ background:#f8f9fa; }
.red-qty{
    border:2px solid #dc3545 !important; /* bootstrap danger */
    font-weight:700;
}
@media print{
    .no-print{display:none}
    body{background:#fff}
    .main-card{box-shadow:none;margin:0}
}
</style>
</head>
<body>

<div class="main-card">

<div class="d-flex justify-content-between align-items-center mb-2">
    <h4 class="mb-0">📦 Manual Stock Adjustment</h4>
    <a class="btn btn-sm btn-outline-danger no-print" href="hps_stock_adjust.php?logout=1">Logout</a>
</div>

<?php if($err!=''): ?>
<div class="alert alert-danger"><?=e($err)?></div>
<?php endif; ?>

<?php if($msg!=''): ?>
<div class="alert alert-success"><?=e($msg)?></div>
<?php endif; ?>

<!-- FILTER -->
<form method="get" class="row g-2 mb-3 no-print">
    <div class="col-md-4">
        <input type="text" name="search" value="<?=e($search_raw)?>"
               class="form-control form-control-sm" placeholder="Search product">
    </div>
    <div class="col-md-2">
        <button class="btn btn-primary btn-sm w-100">Filter</button>
    </div>
    <div class="col-md-2">
        <button type="button" onclick="window.print()" class="btn btn-dark btn-sm w-100">Print</button>
    </div>
</form>

<table class="table table-bordered table-sm align-middle">
    <thead class="table-dark">
        <tr>
            <th style="width:60px">#</th>
            <th>Product</th>
            <th class="text-center" style="width:90px">Reorder</th>
            <th class="text-end" style="width:120px">Current</th>
            <th class="text-end" style="width:110px">Avg Cost</th>
            <th class="text-end" style="width:120px">Value</th>
            <th class="text-center" style="width:120px">Adjust Stock</th>
            <th class="text-end" style="width:120px">Reason</th>
            <th class="text-end" style="width:120px">Action</th>
        </tr>
    </thead>
    <tbody>
    <?php
    $i=1;
    if(mysqli_num_rows($res)==0):
    ?>
        <tr>
            <td colspan="7" class="text-center text-muted">No products found.</td>
        </tr>
    <?php
    else:
        while($r=mysqli_fetch_assoc($res)):
    ?>
        <tr>
            <td><?= $i++ ?></td>
            <td><?= e($r['name']) ?></td>
            <td class="text-center"><?= e($r['reorder_level']) ?></td>
            <td class="text-end fw-bold"><?= e($r['qty_on_hand']) ?></td>
            <td class="text-end"><?= number_format((float)$r['avg_cost'],2) ?></td>
            <td class="text-end"><?= number_format((float)$r['stock_value'],2) ?></td>
            <td>
                <form method="post" class="d-flex gap-2">
                    <input type="hidden" name="product_id" value="<?= (int)$r['id'] ?>">

                    <input type="number" step="0.01" name="new_qty"
                           value="<?= e($r['qty_on_hand']) ?>"
                           class="form-control form-control-sm red-qty"
                           style="width:120px" required>

                    <input type="text" name="reason"
                           placeholder="Reason (e.g. physical count)"
                           class="form-control form-control-sm"
                           style="width:210px" required>

                    <button type="submit" name="save_adjustment"
                            class="btn btn-sm btn-success">
                        Save
                    </button>
                </form>
            </td>
        </tr>
    <?php
        endwhile;
    endif;
    ?>
    </tbody>
</table>

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