<?php
ob_start();
session_start();
require_once '../config/database.php';       // $pdo (Seven Credit DB)
require_once '../config/modules.php';         // company_enabled_modules(), module_on()
require_once '../config/module_access.php';   // mod_can_edit()

if (!isset($_SESSION['user_id']) || empty($_SESSION['company_id'])) {
    header('Location: ../auth/login.php'); exit;
}
$companyId = (int)$_SESSION['company_id'];
$userId    = (int)$_SESSION['user_id'];
$role      = $_SESSION['role'] ?? '';

$enabled = company_enabled_modules($pdo, $companyId);
if (!module_on($enabled, 'stock')) {
    http_response_code(403);
    exit('The Stock Management module is not enabled for your company.');
}
if (!mod_can_view($pdo, $companyId, $userId, $role, 'stock')) {
    http_response_code(403);
    exit('You do not have access to Stock Management. Please ask your admin.');
}

$canEdit = mod_can_edit($pdo, $companyId, $userId, $role, 'stock');

if (!function_exists('esc')) { function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); } }

$companyName = $_SESSION['company_name'] ?? 'Company';

$message = '';
$error   = '';

/*
|--------------------------------------------------------------------------
| Tables (created automatically on first run) — company-scoped
| sp_stock_items    : product master (one row per stock item)
| sp_stock_movements: stock in/out transactions for each item
|--------------------------------------------------------------------------
*/
$pdo->exec("
    CREATE TABLE IF NOT EXISTS sp_stock_items (
        id INT AUTO_INCREMENT PRIMARY KEY,
        company_id INT NOT NULL,
        order_code VARCHAR(100) DEFAULT NULL,
        short_code VARCHAR(255) DEFAULT NULL,
        description TEXT,
        supplier VARCHAR(255) DEFAULT NULL,
        machine_type VARCHAR(100) DEFAULT NULL,
        new_code VARCHAR(100) DEFAULT NULL,
        note TEXT,
        price DECIMAL(15,2) NOT NULL DEFAULT 0,
        reorder_level INT NOT NULL DEFAULT 0,
        color VARCHAR(20) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX (company_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");
if (!$pdo->query("SHOW COLUMNS FROM sp_stock_items LIKE 'color'")->fetch()) {
    $pdo->exec("ALTER TABLE sp_stock_items ADD COLUMN color VARCHAR(20) DEFAULT NULL");
}
$pdo->exec("
    CREATE TABLE IF NOT EXISTS sp_stock_movements (
        id INT AUTO_INCREMENT PRIMARY KEY,
        company_id INT NOT NULL,
        item_id INT NOT NULL,
        move_date DATE DEFAULT NULL,
        direction VARCHAR(10) NOT NULL DEFAULT 'Out',
        qty INT NOT NULL DEFAULT 0,
        cost_price DECIMAL(15,2) NOT NULL DEFAULT 0,
        packing_no VARCHAR(100) DEFAULT NULL,
        customer_name VARCHAR(255) DEFAULT NULL,
        sd_no VARCHAR(50) DEFAULT NULL,
        note VARCHAR(255) DEFAULT NULL,
        machine_no VARCHAR(100) DEFAULT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX (company_id, item_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");
// ensure machine_no exists on older installs
if (!$pdo->query("SHOW COLUMNS FROM sp_stock_movements LIKE 'machine_no'")->fetch()) {
    $pdo->exec("ALTER TABLE sp_stock_movements ADD COLUMN machine_no VARCHAR(100) DEFAULT NULL");
}

/*
|--------------------------------------------------------------------------
| AJAX: look up a machine number -> customer name + SD No (company-scoped)
|--------------------------------------------------------------------------
*/
if (isset($_GET['lookup_machine'])) {
    header('Content-Type: application/json');
    $mno = trim($_GET['lookup_machine']);
    $out = ['found' => false, 'customer_name' => '', 'sd_no' => ''];
    if ($mno !== '') {
        $st = $pdo->prepare("
            SELECT m.sd_no, c.customer_name
            FROM sp_machines m
            LEFT JOIN sp_customers c ON c.company_id = m.company_id AND c.sd_no = m.sd_no
            WHERE m.company_id = ? AND m.unique_machine_no = ? LIMIT 1
        ");
        $st->execute([$companyId, $mno]);
        if ($row = $st->fetch(PDO::FETCH_ASSOC)) {
            $out = ['found' => true, 'customer_name' => (string)($row['customer_name'] ?? ''), 'sd_no' => (string)($row['sd_no'] ?? '')];
        }
    }
    echo json_encode($out);
    exit;
}

/*
|--------------------------------------------------------------------------
| AJAX: live item suggestions for the smart search (with colour)
|--------------------------------------------------------------------------
*/
if (isset($_GET['suggest'])) {
    header('Content-Type: application/json');
    $q = trim($_GET['suggest']);
    $out = [];
    if ($q !== '') {
        $like = '%' . $q . '%';
        $st = $pdo->prepare("SELECT i.id, i.order_code, i.short_code, i.description, i.machine_type, i.color,
                                    COALESCE(SUM(CASE WHEN m.direction='In' THEN m.qty ELSE -m.qty END),0) AS on_hand
                             FROM sp_stock_items i
                             LEFT JOIN sp_stock_movements m ON m.item_id = i.id AND m.company_id = i.company_id
                             WHERE i.company_id = ? AND (i.order_code LIKE ? OR i.short_code LIKE ? OR i.description LIKE ? OR i.machine_type LIKE ?)
                             GROUP BY i.id
                             ORDER BY i.order_code ASC LIMIT 500");
        $st->execute([$companyId, $like, $like, $like, $like]);
        foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $it) {
            $color = stockColor($it);
            $out[] = [
                'id'          => (int)$it['id'],
                'order_code'  => (string)($it['order_code'] ?? ''),
                'short_code'  => (string)($it['short_code'] ?? ''),
                'description' => (string)($it['description'] ?? ''),
                'machine_type'=> (string)($it['machine_type'] ?? ''),
                'color'       => $color,
                'color_hex'   => colorHex($color),
                'on_hand'     => (int)$it['on_hand'],
            ];
        }
    }
    echo json_encode($out);
    exit;
}

/*
|--------------------------------------------------------------------------
| Add new stock item (gated)
|--------------------------------------------------------------------------
*/
if (isset($_POST['add_item'])) {
    if (!$canEdit) { http_response_code(403); exit('You do not have permission to edit stock.'); }
    $stmt = $pdo->prepare("INSERT INTO sp_stock_items (company_id, order_code) VALUES (?, ?)");
    $stmt->execute([$companyId, trim($_POST['new_order_code'] ?? '') ?: 'NEW-' . date('YmdHis')]);
    header('Location: sp_stock.php?item=' . $pdo->lastInsertId());
    exit;
}

/*
|--------------------------------------------------------------------------
| Save (update) stock item master fields (gated, company-scoped)
|--------------------------------------------------------------------------
*/
if (isset($_POST['save_item'])) {
    if (!$canEdit) { http_response_code(403); exit('You do not have permission to edit stock.'); }
    $id = (int)($_POST['item_id'] ?? 0);
    if ($id > 0) {
        $stmt = $pdo->prepare("
            UPDATE sp_stock_items
            SET order_code = ?, short_code = ?, description = ?, supplier = ?,
                machine_type = ?, new_code = ?, note = ?, price = ?, reorder_level = ?, color = ?
            WHERE id = ? AND company_id = ?
        ");
        $stmt->execute([
            trim($_POST['order_code'] ?? ''),
            trim($_POST['short_code'] ?? ''),
            trim($_POST['description'] ?? ''),
            trim($_POST['supplier'] ?? ''),
            trim($_POST['machine_type'] ?? ''),
            trim($_POST['new_code'] ?? ''),
            trim($_POST['note'] ?? ''),
            (float)str_replace(',', '', (string)($_POST['price'] ?? '0')),
            (int)str_replace(',', '', (string)($_POST['reorder_level'] ?? '0')),
            trim($_POST['color'] ?? ''),
            $id,
            $companyId
        ]);
        $message = 'Item saved.';
    }
    header('Location: sp_stock.php?item=' . $id . '&saved=1');
    exit;
}

/*
|--------------------------------------------------------------------------
| Add a stock movement (in / out) — gated, company-scoped
|--------------------------------------------------------------------------
*/
if (isset($_POST['add_movement'])) {
    if (!$canEdit) { http_response_code(403); exit('You do not have permission to edit stock.'); }
    $id = (int)($_POST['item_id'] ?? 0);
    if ($id > 0) {
        // ensure the item belongs to this company before adding a movement
        $chk = $pdo->prepare("SELECT id FROM sp_stock_items WHERE id = ? AND company_id = ? LIMIT 1");
        $chk->execute([$id, $companyId]);
        if ($chk->fetchColumn()) {
            $stmt = $pdo->prepare("
                INSERT INTO sp_stock_movements
                    (company_id, item_id, move_date, direction, qty, cost_price, packing_no, customer_name, sd_no, note, machine_no)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $companyId,
                $id,
                ($_POST['move_date'] ?? '') ?: null,
                ($_POST['direction'] ?? 'Out') === 'In' ? 'In' : 'Out',
                (int)str_replace(',', '', (string)($_POST['qty'] ?? '0')),
                (float)str_replace(',', '', (string)($_POST['cost_price'] ?? '0')),
                trim($_POST['packing_no'] ?? ''),
                trim($_POST['customer_name'] ?? ''),
                trim($_POST['sd_no'] ?? ''),
                trim($_POST['note'] ?? ''),
                trim($_POST['machine_no'] ?? '')
            ]);
        }
    }
    header('Location: sp_stock.php?item=' . $id);
    exit;
}

/*
|--------------------------------------------------------------------------
| Delete a stock movement (gated, company-scoped)
|--------------------------------------------------------------------------
*/
if (isset($_GET['del_move'])) {
    if (!$canEdit) { http_response_code(403); exit('You do not have permission to edit stock.'); }
    $mid = (int)$_GET['del_move'];
    $id  = (int)($_GET['item'] ?? 0);
    if ($mid > 0) {
        $pdo->prepare("DELETE FROM sp_stock_movements WHERE id = ? AND company_id = ?")
            ->execute([$mid, $companyId]);
    }
    header('Location: sp_stock.php?item=' . $id);
    exit;
}

/*
|--------------------------------------------------------------------------
| Update a stock movement (gated, company-scoped)
|--------------------------------------------------------------------------
*/
if (isset($_POST['update_movement'])) {
    if (!$canEdit) { http_response_code(403); exit('You do not have permission to edit stock.'); }
    $mid = (int)($_POST['move_id'] ?? 0);
    $id  = (int)($_POST['item_id'] ?? 0);
    if ($mid > 0) {
        $stmt = $pdo->prepare("
            UPDATE sp_stock_movements
            SET move_date = ?, direction = ?, qty = ?, cost_price = ?, packing_no = ?, customer_name = ?, sd_no = ?, note = ?, machine_no = ?
            WHERE id = ? AND company_id = ?
        ");
        $stmt->execute([
            ($_POST['move_date'] ?? '') ?: null,
            ($_POST['direction'] ?? 'Out') === 'In' ? 'In' : 'Out',
            (int)str_replace(',', '', (string)($_POST['qty'] ?? '0')),
            (float)str_replace(',', '', (string)($_POST['cost_price'] ?? '0')),
            trim($_POST['packing_no'] ?? ''),
            trim($_POST['customer_name'] ?? ''),
            trim($_POST['sd_no'] ?? ''),
            trim($_POST['note'] ?? ''),
            trim($_POST['machine_no'] ?? ''),
            $mid,
            $companyId
        ]);
    }
    header('Location: sp_stock.php?item=' . $id);
    exit;
}

$editMoveId = (int)($_GET['edit_move'] ?? 0);

if (isset($_GET['saved'])) { $message = 'Item saved.'; }

/*
|--------------------------------------------------------------------------
| Item list (with optional search) + current item selection + pagination
| — only this company's items.
|--------------------------------------------------------------------------
*/
$search = trim($_GET['q'] ?? '');

/* All-items list view (button "All Items") */
$showList = isset($_GET['list']);
$allItems = [];
if ($showList) {
    $lsql = "SELECT i.*, COALESCE(SUM(CASE WHEN m.direction='In' THEN m.qty ELSE -m.qty END),0) AS on_hand
             FROM sp_stock_items i
             LEFT JOIN sp_stock_movements m ON m.item_id = i.id AND m.company_id = i.company_id
             WHERE i.company_id = ?";
    $lp = [$companyId];
    if ($search !== '') {
        $lsql .= " AND (i.order_code LIKE ? OR i.short_code LIKE ? OR i.description LIKE ? OR i.machine_type LIKE ?)";
        $lk = '%' . $search . '%'; array_push($lp, $lk, $lk, $lk, $lk);
    }
    $lsql .= " GROUP BY i.id ORDER BY i.order_code ASC, i.id ASC";
    $ls = $pdo->prepare($lsql); $ls->execute($lp); $allItems = $ls->fetchAll();
}

$listSql = "SELECT id FROM sp_stock_items WHERE company_id = ?";
$listParams = [$companyId];
if ($search !== '') {
    $listSql .= " AND (order_code LIKE ? OR short_code LIKE ? OR description LIKE ? OR machine_type LIKE ?) ";
    $like = '%' . $search . '%';
    array_push($listParams, $like, $like, $like, $like);
}
$listSql .= " ORDER BY order_code ASC, id ASC";
$stmt = $pdo->prepare($listSql);
$stmt->execute($listParams);
$itemIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

$totalItems = count($itemIds);
$currentId  = (int)($_GET['item'] ?? 0);
if ($totalItems > 0 && !in_array($currentId, array_map('intval', $itemIds), true)) {
    $currentId = (int)$itemIds[0];
}

$item = null;
if ($currentId > 0) {
    $stmt = $pdo->prepare("SELECT * FROM sp_stock_items WHERE id = ? AND company_id = ? LIMIT 1");
    $stmt->execute([$currentId, $companyId]);
    $item = $stmt->fetch();
}

// pagination neighbours
$idx      = $item ? array_search($currentId, array_map('intval', $itemIds), true) : false;
$firstId  = $totalItems ? (int)$itemIds[0] : 0;
$lastId   = $totalItems ? (int)$itemIds[$totalItems - 1] : 0;
$prevId   = ($idx !== false && $idx > 0) ? (int)$itemIds[$idx - 1] : $currentId;
$nextId   = ($idx !== false && $idx < $totalItems - 1) ? (int)$itemIds[$idx + 1] : $currentId;
$position = ($idx !== false) ? $idx + 1 : 0;

/*
|--------------------------------------------------------------------------
| Movements + computed metrics for current item (company-scoped)
|--------------------------------------------------------------------------
*/
$movements = [];
$onHand = 0;
if ($item) {
    $stmt = $pdo->prepare("SELECT * FROM sp_stock_movements WHERE item_id = ? AND company_id = ? ORDER BY move_date ASC, id ASC");
    $stmt->execute([$currentId, $companyId]);
    $movements = $stmt->fetchAll();
    foreach ($movements as $mv) {
        $onHand += ($mv['direction'] === 'In') ? (int)$mv['qty'] : -(int)$mv['qty'];
    }
}
$price        = $item ? (float)$item['price'] : 0;
$reorderLevel = $item ? (int)$item['reorder_level'] : 0;
$amount       = $onHand * $price;

if (!$item) {
    $stockLabel = 'No item'; $stockClass = 'st-none';
} elseif ($onHand <= 0) {
    $stockLabel = 'Out of stock'; $stockClass = 'st-out';
} elseif ($onHand <= $reorderLevel) {
    $stockLabel = 'Low stock'; $stockClass = 'st-low';
} else {
    $stockLabel = 'In stock'; $stockClass = 'st-in';
}

function fmt($n) { return number_format((float)$n, 2); }
// value for money inputs: commas, trailing .00 trimmed (e.g. 965600 -> "965,600")
function mnum($n) { return rtrim(rtrim(number_format((float)$n, 2), '0'), '.'); }

// resolve an item's toner colour: use the saved color, else best-effort detect from text
function stockColor(array $it): string {
    $c = strtolower(trim((string)($it['color'] ?? '')));
    $map = ['cyan'=>'Cyan','magenta'=>'Magenta','yellow'=>'Yellow','black'=>'Black','other'=>'Other'];
    if (isset($map[$c])) return $map[$c];
    $t = ' ' . strtoupper((string)($it['order_code'] ?? '') . ' ' . ($it['short_code'] ?? '') . ' ' . ($it['description'] ?? '')) . ' ';
    if (strpos($t,'CYAN') !== false) return 'Cyan';
    if (strpos($t,'MAGENTA') !== false) return 'Magenta';
    if (strpos($t,'YELLOW') !== false) return 'Yellow';
    if (strpos($t,'BLACK') !== false) return 'Black';
    return '';
}
function colorHex(string $color): string {
    switch ($color) {
        case 'Cyan': return '#06b6d4';
        case 'Magenta': return '#db2777';
        case 'Yellow': return '#eab308';
        case 'Black': return '#111827';
        case 'Other': return '#64748b';
        default: return '#cbd5e1';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stock Management</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Lao:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg: #f3f6fb; --card: #fff; --ink: #111827; --muted: #64748b; --line: #e6eaf2;
            --brand: #2563eb; --brand2: #1d4ed8;
            --shadow: 0 12px 30px rgba(30,41,59,.08); --shadow-sm: 0 2px 6px rgba(30,41,59,.06);
        }
        * { box-sizing: border-box; }
        body { margin: 0; font-family: 'Noto Sans Lao','Inter',Arial,sans-serif; background: var(--bg); color: var(--ink); }
        .wrap { max-width: 1280px; margin: 0 auto; padding: 10px 16px 16px; }

        .title-wrap { display: flex; align-items: center; gap: 12px; }
        a.back {
            background: #fff; border: 1px solid var(--line); padding: 7px 13px;
            border-radius: 999px; text-decoration: none; color: #475569; font-weight: 600;
            font-size: 13px; box-shadow: var(--shadow-sm); white-space: nowrap;
        }
        a.back:hover { color: var(--brand); border-color: #bfdbfe; }

        .page-head { display: flex; align-items: center; justify-content: space-between; gap: 14px; flex-wrap: wrap; margin-bottom: 10px; }
        .page-head h1 { margin: 0; font-size: 22px; font-weight: 800; }
        .card { background: var(--card); border: 1px solid var(--line); border-radius: 14px; box-shadow: var(--shadow); padding: 14px 16px; margin-bottom: 12px; }
        .btn { background: var(--brand); color: #fff; border: none; padding: 10px 16px; border-radius: 10px; cursor: pointer; font-weight: 700; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; font-size: 14px; font-family: inherit; }
        .btn:hover { background: var(--brand2); }
        .btn-add { background: #059669; } .btn-add:hover { background: #047857; }
        .btn-clear { background: #eef2f7; color: #475569; } .btn-clear:hover { background: #e2e8f0; }
        .message { background: #ecfdf5; color: #047857; padding: 12px 15px; border-radius: 12px; margin-bottom: 14px; border: 1px solid #a7f3d0; font-weight: 600; }
        .error { background: #fef2f2; color: #b91c1c; padding: 12px 15px; border-radius: 12px; margin-bottom: 14px; border: 1px solid #fecaca; font-weight: 600; }
        .viewonly { background: #eff6ff; color: #1d4ed8; padding: 10px 14px; border-radius: 12px; margin-bottom: 14px; border: 1px solid #bfdbfe; font-weight: 600; font-size: 13px; }

        /* top search + metrics */
        .top-grid { display: grid; grid-template-columns: 300px 1fr; gap: 12px; align-items: stretch; margin-bottom: 12px; }
        /* movements list scrolls on its own; the cards above stay put */
        .mv-scroll { max-height: calc(100vh - 430px); min-height: 180px; overflow-y: auto; }
        .mv-scroll thead th { position: sticky; top: 0; z-index: 3; }
        .search-box label { display: block; font-size: 12px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: .04em; margin-bottom: 6px; }
        .search-box .search-row { display: flex; gap: 8px; }
        .search-box input { flex: 1; padding: 12px 14px; border: 1px solid #e2e8f0; border-radius: 10px; font-size: 15px; font-family: inherit; background: #f8fafc; }
        .metrics { display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; }
        .metric { background: #fff; border: 1px solid var(--line); border-radius: 12px; padding: 9px 12px; box-shadow: var(--shadow-sm); }
        .metric .label { font-size: 11px; color: var(--muted); font-weight: 600; text-transform: uppercase; letter-spacing: .03em; }
        .metric .value { font-size: 19px; font-weight: 800; margin-top: 2px; }
        .status { display: grid; place-items: center; border-radius: 14px; font-weight: 800; font-size: 18px; color: #fff; }
        .st-in { background: #16a34a; } .st-low { background: #d97706; } .st-out { background: #dc2626; } .st-none { background: #94a3b8; }

        /* main two-column */
        .main-grid { display: grid; grid-template-columns: 1fr; gap: 16px; align-items: start; }
        .field { margin-bottom: 12px; }
        /* horizontal item-master layout */
        .field-row { display: flex; flex-wrap: wrap; gap: 14px; }
        .field-row .field { flex: 1 1 150px; margin-bottom: 0; }
        .field-row .field.fx-wide { flex: 2 1 280px; }
        /* movement table: center all columns except Customer Name (7) and Note (9) */
        .mv-table th, .mv-table td { text-align: center; }
        .mv-table th:nth-child(7), .mv-table td:nth-child(7),
        .mv-table th:nth-child(9), .mv-table td:nth-child(9) { text-align: left; }
        .mv-table .mv-input { text-align: center; }
        .mv-table td:nth-child(7) .mv-input, .mv-table td:nth-child(9) .mv-input { text-align: left; }
        .mv-table td:nth-child(7) .sd-pill { }
        .field label { display: block; font-size: 12px; font-weight: 700; color: var(--muted); text-transform: uppercase; letter-spacing: .03em; margin-bottom: 5px; }
        .field input, .field textarea { width: 100%; padding: 10px 12px; border: 1px solid #e2e8f0; border-radius: 10px; font-size: 14px; font-family: inherit; background: #fff; }
        .field textarea { min-height: 70px; resize: vertical; }
        .field .highlight { background: #fef9c3; border-color: #fde047; font-weight: 700; }
        .order-code { color: #dc2626; }
        .two { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }

        .table-scroll { overflow-x: auto; border-radius: 12px; }
        table { width: 100%; border-collapse: collapse; min-width: 900px; }
        thead th { background: #f8fafc; color: var(--muted); text-transform: uppercase; font-size: 11px; letter-spacing: .04em; font-weight: 700; padding: 10px 8px; text-align: left; border-bottom: 1px solid var(--line); white-space: nowrap; }
        tbody td { padding: 8px; border-bottom: 1px solid var(--line); font-size: 13px; white-space: nowrap; }
        tbody tr:hover { background: #f9fafe; }
        .mv-input { width: 100%; padding: 8px 9px; border: 1px solid #e2e8f0; border-radius: 8px; font-size: 13px; font-family: inherit; background: #fff; }
        .sd-pill { display: inline-block; background: #dcfce7; color: #166534; padding: 3px 9px; border-radius: 6px; font-weight: 700; font-size: 12px; text-decoration: none; }
        .dir-in { color: #16a34a; font-weight: 700; } .dir-out { color: #dc2626; font-weight: 700; }
        .del-x { color: #dc2626; text-decoration: none; font-weight: 800; padding: 4px 8px; border-radius: 6px; }
        /* remove up/down spinner arrows on all number fields */
        input[type=number]::-webkit-outer-spin-button,
        input[type=number]::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
        input[type=number] { -moz-appearance: textfield; }
        .mv-edit { color: #2563eb; text-decoration: none; font-weight: 700; padding: 4px 8px; border-radius: 6px; margin-right: 2px; }
        .mv-edit:hover { background: #eff6ff; }
        .del-x:hover { background: #fef2f2; }

        .pager { display: flex; gap: 8px; justify-content: center; margin-top: 18px; align-items: center; }
        .pager a { background: #eef2f7; color: #334155; padding: 9px 16px; border-radius: 10px; text-decoration: none; font-weight: 700; }
        .pager a:hover { background: #e2e8f0; }
        .pager .pos { color: var(--muted); font-weight: 600; margin: 0 8px; }

        @media (max-width: 900px) {
            .top-grid { grid-template-columns: 1fr; }
            .metrics { grid-template-columns: repeat(2, 1fr); }
            .main-grid { grid-template-columns: 1fr; }
        }
        /* smart-search autocomplete */
        .ac-results {
            position: absolute; top: calc(100% + 4px); left: 0; right: auto; z-index: 50;
            width: min(820px, 92vw);
            background: #fff; border: 1px solid #e2e8f0; border-radius: 12px;
            box-shadow: 0 12px 30px rgba(30,41,59,.16); max-height: 62vh; overflow-y: auto; display: none;
            padding: 12px; gap: 16px; flex-wrap: wrap; align-items: flex-start;
        }
        .ac-results.show { display: flex; }
        .ac-col { display: flex; flex-direction: column; gap: 3px; min-width: 190px; }
        .ac-col-head {
            font-size: 11px; font-weight: 800; text-transform: uppercase; letter-spacing: .04em;
            color: #334155; border-bottom: 2px solid #e2e8f0; padding: 0 4px 5px; margin-bottom: 3px;
        }
        .ac-row { display: flex; align-items: center; gap: 6px; padding: 6px 8px; border-radius: 8px; cursor: pointer; }
        .ac-row:hover { background: #eff6ff; }
        .ac-dot { width: 14px; height: 14px; border-radius: 4px; flex: 0 0 auto; border: 1px solid rgba(0,0,0,.15); }
        .ac-cname { font-size: 11px; font-weight: 700; color: #64748b; }
        .ac-code { font-weight: 800; font-size: 14px; color: #0f172a; }
        .ac-qty { margin-left: auto; min-width: 26px; text-align: center; font-weight: 800; font-size: 13px; color: #166534; background: #dcfce7; border-radius: 999px; padding: 2px 8px; }
        .ac-qty-out { color: #b91c1c; background: #fee2e2; }
        .ac-empty { padding: 10px 12px; color: #94a3b8; font-size: 13px; width: 100%; }
        .color-chip { display: inline-flex; align-items: center; gap: 6px; }
        .color-dot { width: 12px; height: 12px; border-radius: 4px; border: 1px solid rgba(0,0,0,.15); display: inline-block; }
    </style>
</head>
<body>
    <div class="wrap">

        <?php $spActive = $showList ? 'allitems' : 'stock'; include 'sp_nav.php'; ?>

        <div class="page-head">
            <div class="title-wrap">
                <h1>Stock Management</h1>
            </div>
            <div style="display:flex; gap:8px; flex-wrap:wrap;">
                <?php if ($showList): ?>
                    <a href="sp_stock.php" class="btn btn-clear">&larr; Item View</a>
                <?php endif; ?>
                <?php if ($canEdit): ?>
                <form method="POST" onsubmit="return true;">
                    <input type="hidden" name="new_order_code" value="">
                    <button type="submit" name="add_item" class="btn btn-add">+ Add Item</button>
                </form>
                <?php endif; ?>
            </div>
        </div>

        <?php if (!$canEdit): ?><div class="viewonly">View-only access. You can browse items, metrics and movement history but cannot make changes.</div><?php endif; ?>
        <?php if ($message): ?><div class="message"><?= esc($message) ?></div><?php endif; ?>
        <?php if ($error): ?><div class="error"><?= esc($error) ?></div><?php endif; ?>

        <?php if ($showList): ?>
        <!-- All items list -->
        <div class="card">
            <form method="GET" class="search-row" style="display:flex; gap:8px; margin-bottom:14px;">
                <input type="hidden" name="list" value="1">
                <input type="text" name="q" placeholder="Search order / short code, description, machine type..." value="<?= esc($search) ?>" style="flex:1; padding:11px 14px; border:1px solid #e2e8f0; border-radius:10px; font-size:14px; font-family:inherit; background:#f8fafc;">
                <button type="submit" class="btn">Search</button>
                <?php if ($search !== ''): ?><a href="sp_stock.php?list=1" class="btn btn-clear">X</a><?php endif; ?>
            </form>
            <div style="color:var(--muted); font-size:13px; margin-bottom:10px;"><?= count($allItems) ?> item(s)</div>
            <div class="table-scroll">
                <table>
                    <thead>
                        <tr>
                            <th>Order Code</th><th>Short Code</th><th>Description</th><th>Type</th>
                            <th>On Hand</th><th>Price</th><th>Amount</th><th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($allItems): ?>
                            <?php foreach ($allItems as $it):
                                $oh = (int)$it['on_hand']; $rl = (int)$it['reorder_level'];
                                $cls = $oh <= 0 ? 'st-out' : ($oh <= $rl ? 'st-low' : 'st-in');
                                $lbl = $oh <= 0 ? 'Out of stock' : ($oh <= $rl ? 'Low' : 'In stock');
                            ?>
                                <tr style="cursor:pointer;" onclick="location.href='sp_stock.php?item=<?= (int)$it['id'] ?>'">
                                    <td><a href="sp_stock.php?item=<?= (int)$it['id'] ?>" style="color:#dc2626; font-weight:700; text-decoration:none;"><?= esc($it['order_code']) ?></a></td>
                                    <td><?= esc($it['short_code']) ?></td>
                                    <td style="white-space:normal; max-width:280px;"><?= esc($it['description']) ?></td>
                                    <td><?= esc($it['machine_type']) ?></td>
                                    <td><strong><?= esc($oh) ?></strong></td>
                                    <td><?= fmt($it['price']) ?></td>
                                    <td><?= fmt($oh * (float)$it['price']) ?></td>
                                    <td><span class="status <?= $cls ?>" style="display:inline-block; padding:3px 10px; border-radius:999px; color:#fff; font-size:12px; font-weight:700;"><?= esc($lbl) ?></span></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="8" style="text-align:center; color:var(--muted);">No items found.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php else: ?>

        <!-- Search + metrics -->
        <div class="top-grid">
            <div class="card search-box">
                <label>Search</label>
                <form method="GET" class="search-row" style="position:relative;" autocomplete="off">
                    <div style="position:relative; flex:1;">
                        <input type="text" name="q" id="ac-input" placeholder="Type code / description..." value="<?= esc($search) ?>" autocomplete="off">
                        <div id="ac-results" class="ac-results"></div>
                    </div>
                    <?php if ($search !== ''): ?>
                        <a href="sp_stock.php" class="btn btn-clear">X</a>
                    <?php else: ?>
                        <button type="submit" class="btn">Go</button>
                    <?php endif; ?>
                </form>
                <div style="margin-top:10px; color:var(--muted); font-size:13px;">
                    <?= $totalItems ? esc($totalItems) . ' item(s)' : 'No items yet' ?> &middot; start typing to pick by colour
                </div>
            </div>

            <div class="card">
                <div class="metrics">
                    <div class="metric"><div class="label">Unit On Hand</div><div class="value"><?= esc($onHand) ?></div></div>
                    <div class="metric"><div class="label">Price</div><div class="value"><?= fmt($price) ?></div></div>
                    <div class="metric"><div class="label">Amount</div><div class="value"><?= fmt($amount) ?></div></div>
                    <div class="metric"><div class="label">Reorder Level</div><div class="value"><?= esc($reorderLevel) ?></div></div>
                    <div class="metric status <?= $stockClass ?>"><?= esc($stockLabel) ?></div>
                </div>
            </div>
        </div>

        <?php if (!$item): ?>
            <div class="card" style="text-align:center; color:var(--muted); padding:40px;">
                <?php if ($canEdit): ?>
                    No stock item selected. Click <strong>+ Add Item</strong> to create your first item.
                <?php else: ?>
                    No stock items to display.
                <?php endif; ?>
            </div>
        <?php else: ?>
        <div class="main-grid">

            <!-- Item master -->
            <div class="card">
                <form method="POST">
                    <input type="hidden" name="item_id" value="<?= esc($item['id']) ?>">

                    <div class="field-row">
                        <div class="field">
                            <label>Order Code</label>
                            <input class="highlight order-code" type="text" name="order_code" value="<?= esc($item['order_code']) ?>"<?= $canEdit ? '' : ' readonly' ?>>
                        </div>
                        <div class="field">
                            <label>Short Code</label>
                            <input class="highlight" type="text" name="short_code" value="<?= esc($item['short_code']) ?>"<?= $canEdit ? '' : ' readonly' ?>>
                        </div>
                        <div class="field fx-wide">
                            <label>Description</label>
                            <input type="text" name="description" value="<?= esc($item['description']) ?>"<?= $canEdit ? '' : ' readonly' ?>>
                        </div>
                        <div class="field fx-wide">
                            <label>Supplier</label>
                            <input type="text" name="supplier" value="<?= esc($item['supplier']) ?>"<?= $canEdit ? '' : ' readonly' ?>>
                        </div>
                        <div class="field">
                            <label>Type</label>
                            <input type="text" name="machine_type" value="<?= esc($item['machine_type']) ?>"<?= $canEdit ? '' : ' readonly' ?>>
                        </div>
                        <div class="field">
                            <label>Color</label>
                            <select name="color"<?= $canEdit ? '' : ' disabled' ?>>
                                <?php $cc = (string)($item['color'] ?? ''); foreach (['','Cyan','Magenta','Yellow','Black','Other'] as $co): ?>
                                    <option value="<?= esc($co) ?>" <?= $cc === $co ? 'selected' : '' ?>><?= $co === '' ? '— none —' : esc($co) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="field">
                            <label>New Code</label>
                            <input type="text" name="new_code" value="<?= esc($item['new_code']) ?>"<?= $canEdit ? '' : ' readonly' ?>>
                        </div>
                        <div class="field">
                            <label>Price</label>
                            <input type="text" inputmode="decimal" class="moneyfmt" name="price" value="<?= esc(mnum($item['price'])) ?>" oninput="fmtMoney(this)"<?= $canEdit ? '' : ' readonly' ?>>
                        </div>
                        <div class="field">
                            <label>Reorder Level</label>
                            <input type="number" name="reorder_level" value="<?= esc($item['reorder_level']) ?>"<?= $canEdit ? '' : ' readonly' ?>>
                        </div>
                        <div class="field fx-wide">
                            <label>Note</label>
                            <input type="text" name="note" value="<?= esc($item['note']) ?>"<?= $canEdit ? '' : ' readonly' ?>>
                        </div>
                    </div>

                    <?php if ($canEdit): ?>
                    <button type="submit" name="save_item" class="btn" style="margin-top:14px;">Save Item</button>
                    <?php endif; ?>
                </form>
            </div>

            <!-- Movements -->
            <div class="card">
                <div class="table-scroll mv-scroll">
                    <table class="mv-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Stock In/Out</th>
                                <th>Qty</th>
                                <th>Machine No</th>
                                <th>Cost Price</th>
                                <th>Packing No</th>
                                <th>Customer Name</th>
                                <th>SD No</th>
                                <th>Note</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($movements): ?>
                                <?php foreach ($movements as $mv): ?>
                                    <?php $isEditMv = ($canEdit && $editMoveId === (int)$mv['id']); ?>
                                    <?php if ($isEditMv): ?>
                                    <tr>
                                        <td><input class="mv-input" type="date" name="move_date" value="<?= esc($mv['move_date']) ?>" form="editmv"></td>
                                        <td>
                                            <select class="mv-input" name="direction" form="editmv" style="width:80px;">
                                                <option value="Out" <?= $mv['direction']==='Out'?'selected':'' ?>>Out</option>
                                                <option value="In" <?= $mv['direction']==='In'?'selected':'' ?>>In</option>
                                            </select>
                                        </td>
                                        <td><input class="mv-input" type="number" name="qty" value="<?= esc($mv['qty']) ?>" form="editmv" style="width:70px;"></td>
                                        <td><input class="mv-input" type="text" id="edit_machine_no" name="machine_no" value="<?= esc($mv['machine_no'] ?? '') ?>" form="editmv" placeholder="Machine No" style="width:100px;" onchange="mLookup(this,'edit_customer_name','edit_sd_no')"></td>
                                        <td><input class="mv-input moneyfmt" type="text" inputmode="decimal" name="cost_price" value="<?= esc(mnum($mv['cost_price'])) ?>" form="editmv" style="min-width:120px;" oninput="fmtMoney(this)"></td>
                                        <td><input class="mv-input" type="text" name="packing_no" value="<?= esc($mv['packing_no']) ?>" form="editmv"></td>
                                        <td><input class="mv-input" type="text" id="edit_customer_name" name="customer_name" value="<?= esc($mv['customer_name']) ?>" form="editmv"></td>
                                        <td><input class="mv-input" type="text" id="edit_sd_no" name="sd_no" value="<?= esc($mv['sd_no']) ?>" form="editmv" style="width:90px;"></td>
                                        <td style="min-width:220px;"><input class="mv-input" type="text" name="note" value="<?= esc($mv['note']) ?>" form="editmv" style="min-width:200px;"></td>
                                        <td style="white-space:nowrap;">
                                            <input type="hidden" name="move_id" value="<?= esc($mv['id']) ?>" form="editmv">
                                            <button type="submit" name="update_movement" class="btn" form="editmv" style="padding:8px 10px;">Save</button>
                                            <a class="del-x" href="sp_stock.php?item=<?= esc($currentId) ?>" style="text-decoration:none;">Cancel</a>
                                        </td>
                                    </tr>
                                    <?php else: ?>
                                    <tr>
                                        <td><?= $mv['move_date'] ? esc(date('d/m/Y', strtotime($mv['move_date']))) : '' ?></td>
                                        <td><?= $mv['direction'] === 'In' ? '<span class="dir-in">In</span>' : '<span class="dir-out">Out</span>' ?></td>
                                        <td><strong><?= esc($mv['qty']) ?></strong></td>
                                        <td><?= esc($mv['machine_no'] ?? '') ?></td>
                                        <td><?= fmt($mv['cost_price']) ?></td>
                                        <td><?= esc($mv['packing_no']) ?></td>
                                        <td><?= esc($mv['customer_name']) ?></td>
                                        <td><?php if (!empty($mv['sd_no'])): ?><a class="sd-pill" href="sp_customer_expenses.php?sd=<?= urlencode($mv['sd_no']) ?>"><?= esc($mv['sd_no']) ?></a><?php endif; ?></td>
                                        <td><?= esc($mv['note']) ?></td>
                                        <td style="white-space:nowrap;">
                                            <?php if ($canEdit): ?>
                                                <a class="mv-edit" href="sp_stock.php?item=<?= esc($currentId) ?>&edit_move=<?= esc($mv['id']) ?>">Edit</a>
                                                <a class="del-x" href="sp_stock.php?del_move=<?= esc($mv['id']) ?>&item=<?= esc($currentId) ?>" onclick="return confirm('Delete this movement?')">&times;</a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                <?php endforeach; ?>
                            <?php endif; ?>

                            <?php if ($canEdit): ?>
                            <!-- add movement row (inputs attach to #addmv form) -->
                                <tr>
                                    <td><input class="mv-input" type="date" name="move_date" value="<?= date('Y-m-d') ?>" form="addmv"></td>
                                    <td>
                                        <select class="mv-input" name="direction" form="addmv" style="width:80px;">
                                            <option value="Out">Out</option>
                                            <option value="In">In</option>
                                        </select>
                                    </td>
                                    <td><input class="mv-input" type="number" name="qty" placeholder="Qty" form="addmv" style="width:70px;"></td>
                                    <td><input class="mv-input" type="text" id="add_machine_no" name="machine_no" placeholder="Machine No" form="addmv" style="width:100px;" onchange="mLookup(this,'add_customer_name','add_sd_no')"></td>
                                    <td><input class="mv-input moneyfmt" type="text" inputmode="decimal" name="cost_price" placeholder="Cost" form="addmv" value="<?= esc(mnum($item['price'])) ?>" style="min-width:120px;" oninput="fmtMoney(this)"></td>
                                    <td><input class="mv-input" type="text" name="packing_no" placeholder="Packing" form="addmv"></td>
                                    <td><input class="mv-input" type="text" id="add_customer_name" name="customer_name" placeholder="Customer" form="addmv"></td>
                                    <td><input class="mv-input" type="text" id="add_sd_no" name="sd_no" placeholder="SD No" form="addmv" style="width:90px;"></td>
                                    <td style="min-width:220px;"><input class="mv-input" type="text" name="note" placeholder="Note" form="addmv" style="min-width:200px;"></td>
                                    <td><button type="submit" name="add_movement" class="btn" form="addmv" style="padding:8px 12px;">Add</button></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <?php if ($canEdit): ?>
                <form id="addmv" method="POST">
                    <input type="hidden" name="item_id" value="<?= esc($item['id']) ?>">
                </form>
                <form id="editmv" method="POST">
                    <input type="hidden" name="item_id" value="<?= esc($item['id']) ?>">
                </form>
                <?php endif; ?>
            </div>

        </div>

        <!-- pagination -->
        <div class="pager">
            <a href="sp_stock.php?item=<?= $firstId ?><?= $search !== '' ? '&q=' . urlencode($search) : '' ?>">&laquo;</a>
            <a href="sp_stock.php?item=<?= $prevId ?><?= $search !== '' ? '&q=' . urlencode($search) : '' ?>">&lsaquo;</a>
            <span class="pos"><?= esc($position) ?> / <?= esc($totalItems) ?></span>
            <a href="sp_stock.php?item=<?= $nextId ?><?= $search !== '' ? '&q=' . urlencode($search) : '' ?>">&rsaquo;</a>
            <a href="sp_stock.php?item=<?= $lastId ?><?= $search !== '' ? '&q=' . urlencode($search) : '' ?>">&raquo;</a>
        </div>
        <?php endif; ?>
        <?php endif; /* showList */ ?>

    </div>
    <script>
        // Smart search: live suggestions with colour, click to open the item
        (function () {
            var input = document.getElementById('ac-input');
            var box   = document.getElementById('ac-results');
            if (!input || !box) return;
            var timer = null, items = [], active = -1;

            function render() {
                if (!items.length) { box.innerHTML = '<div class="ac-empty">No matching items.</div>'; box.classList.add('show'); return; }
                // group by Type
                var groups = {}, order = [];
                items.forEach(function (it) {
                    var t = (it.machine_type && it.machine_type.trim()) ? it.machine_type.trim() : 'Other';
                    if (!groups[t]) { groups[t] = []; order.push(t); }
                    groups[t].push(it);
                });
                box.innerHTML = order.map(function (type) {
                    var rows = groups[type].map(function (it) {
                        var code = it.order_code || it.short_code || '(no code)';
                        var qcls = it.on_hand <= 0 ? ' ac-qty-out' : '';
                        return '<div class="ac-row" data-id="' + it.id + '" title="' + escapeHtml(it.description || '') + '">' +
                            '<span class="ac-dot" style="background:' + it.color_hex + '"></span>' +
                            (it.color ? '<span class="ac-cname">' + it.color + '</span>' : '') +
                            '<span class="ac-code">' + escapeHtml(code) + '</span>' +
                            '<span class="ac-qty' + qcls + '">' + it.on_hand + '</span></div>';
                    }).join('');
                    return '<div class="ac-col"><div class="ac-col-head">' + escapeHtml(type) + '</div>' + rows + '</div>';
                }).join('');
                box.classList.add('show');
                box.querySelectorAll('.ac-row').forEach(function (el) {
                    el.addEventListener('mousedown', function (e) { e.preventDefault(); location.href = 'sp_stock.php?item=' + el.getAttribute('data-id'); });
                });
            }
            function escapeHtml(s){ return (s||'').replace(/[&<>"]/g, function(c){ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]; }); }

            input.addEventListener('input', function () {
                var q = input.value.trim();
                active = -1;
                clearTimeout(timer);
                if (q.length < 2) { box.classList.remove('show'); return; }
                timer = setTimeout(function () {
                    fetch('sp_stock.php?suggest=' + encodeURIComponent(q))
                        .then(function (r) { return r.json(); })
                        .then(function (d) { items = d || []; render(); })
                        .catch(function () {});
                }, 180);
            });
            input.addEventListener('keydown', function (e) {
                if (e.key === 'Escape') { box.classList.remove('show'); }
            });
            document.addEventListener('click', function (e) { if (!box.contains(e.target) && e.target !== input) box.classList.remove('show'); });
        })();

        // Format a money field with thousands separators as the user types
        function fmtMoney(el) {
            var caret = el.selectionStart;
            var digitsBefore = el.value.slice(0, caret).replace(/[^0-9]/g, '').length;
            var raw = el.value.replace(/[^0-9.]/g, '');
            var parts = raw.split('.');
            var intp = parts[0].replace(/^0+(?=\d)/, '');
            var dec = parts.length > 1 ? '.' + parts.slice(1).join('').slice(0, 2) : '';
            var out = (intp === '' ? (dec ? '0' : '') : Number(intp).toLocaleString('en-US')) + dec;
            el.value = out;
            var pos = 0, seen = 0;
            while (pos < out.length && seen < digitsBefore) { if (/[0-9]/.test(out[pos])) seen++; pos++; }
            try { el.setSelectionRange(pos, pos); } catch (e) {}
        }
        // Look up a machine number -> auto-fill customer name + SD No
        function mLookup(el, custId, sdId) {
            var v = (el.value || '').trim();
            if (!v) return;
            fetch('sp_stock.php?lookup_machine=' + encodeURIComponent(v))
                .then(function (r) { return r.json(); })
                .then(function (d) {
                    if (d && d.found) {
                        var c = document.getElementById(custId);
                        var s = document.getElementById(sdId);
                        if (c) c.value = d.customer_name;
                        if (s) s.value = d.sd_no;
                    }
                })
                .catch(function () {});
        }
    </script>
</body>
</html>