<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

date_default_timezone_set('Asia/Beirut');
function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

// --- إدارة اللغة ---
$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'ar');
if (isset($_GET['lang'])) {
    $_SESSION['lang'] = $_GET['lang'] === 'ar' ? 'ar' : 'en';
    $lang = $_SESSION['lang'];
}
$is_ar = ($lang === 'ar');
$nameField = 'name_en'; 

$action = $_GET['action'] ?? ($_POST['action'] ?? null);

// ==================================
// AJAX — تحديث ذكي (تعديل سريع)
// ==================================
if (isset($_GET['update_field']) && $_GET['update_field'] == '1') {
    header('Content-Type: application/json');
    $id = intval($_POST['id']);
    $field = $_POST['field'];
    $value = $_POST['value'];
    
    $allowed_fields = ['stock', 'price', 'cost'];
    if (in_array($field, $allowed_fields)) {
        $stmt = $pdo->prepare("UPDATE products SET $field = ? WHERE id = ?");
        if ($stmt->execute([$value, $id])) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Database error']);
        }
    }
    exit;
}

// ==================================
// AJAX — منطق البحث والتصفية (إخفاء الكمية 0)
// ==================================
if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    $q = trim($_GET['q'] ?? '');
    $filter = $_GET['filter'] ?? 'all';
    $page = max(1, intval($_GET['page'] ?? 1));
    $perPage = 40;
    $offset = ($page - 1) * $perPage;

    $params = [];
    // القاعدة الأساسية: إخفاء المنتجات التي كميتها 0 أو أقل
    $where = "WHERE stock > 0";

    if ($q !== '') {
        $where .= " AND ({$nameField} LIKE :q1 OR sku LIKE :q2 OR id = :id)";
        $params[':q1'] = "%$q%";
        $params[':q2'] = "%$q%";
        $params[':id'] = is_numeric($q) ? intval($q) : -1;
    }

    if ($filter === 'low') $where .= " AND stock <= 5";

    $order = "ORDER BY CASE 
                WHEN sku = :exact THEN 1 
                WHEN sku LIKE :start_sku THEN 2 
                WHEN {$nameField} LIKE :start_name THEN 3 
                ELSE 4 END, id DESC";
    
    $params[':exact'] = $q;
    $params[':start_sku'] = "$q%";
    $params[':start_name'] = "$q%";

    $sql = "SELECT id, sku, {$nameField} AS name, cost, price, stock, created_at FROM products $where $order LIMIT $perPage OFFSET $offset";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $countSql = "SELECT COUNT(*) FROM products $where";
    $countStmt = $pdo->prepare($countSql);
    $countParams = array_intersect_key($params, [':q1'=>1,':q2'=>1,':id'=>1]);
    $countStmt->execute($countParams);
    $total = intval($countStmt->fetchColumn() ?: 0);

    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'rows' => $rows, 'total' => $total, 'page' => $page, 'perPage' => $perPage]);
    exit;
}

// ==================================
// منطق إضافة منتج وتصدير
// ==================================
if ($_SERVER['REQUEST_METHOD']==='POST' && $action==='add_product'){
    $sku = trim($_POST['sku']);
    $name = trim($_POST['name']);
    $cost = floatval($_POST['cost']);
    $price = floatval($_POST['price']);
    $stock = intval($_POST['stock']);
    if ($name !== ''){
        $stmt=$pdo->prepare("INSERT INTO products (sku, {$nameField}, cost, price, stock, created_at) VALUES (?,?,?,?,?,NOW())");
        $stmt->execute([$sku,$name,$cost,$price,$stock]);
        header("Location: inventory.php?success=1"); exit;
    }
}

// الإحصائيات الآن تشمل فقط المنتجات المتوفرة (stock > 0) بناءً على طلبك
$summary = $pdo->query("SELECT COUNT(*) total_p, SUM(stock) total_s, SUM(cost*stock) total_v, SUM(CASE WHEN stock <= 5 AND stock > 0 THEN 1 ELSE 0 END) low_c FROM products WHERE stock > 0")->fetch();
?>
<!doctype html>
<html lang="<?= $is_ar?'ar':'en' ?>" dir="<?= $is_ar?'rtl':'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Premium Inventory Hub</title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        :root {
            --accent-blue: #2563eb;
            --accent-indigo: #4f46e5;
            --surface-primary: #ffffff;
            --surface-secondary: #f8fafc;
            --border-subtle: #e2e8f0;
            --text-main: #0f172a;
            --text-dim: #64748b;
        }

        body {
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Plus Jakarta Sans', sans-serif" ?>;
            background-color: #f1f5f9;
            color: var(--text-main);
            overflow-x: hidden;
        }

        /* Premium Top Nav */
        .premium-nav {
            background: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid var(--border-subtle);
            position: sticky; top: 0; z-index: 1050;
            padding: 10px 0;
        }

        /* Modern Dashboard Stats */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-tile {
            background: var(--surface-primary);
            border-radius: 24px;
            padding: 25px;
            border: 1px solid var(--border-subtle);
            box-shadow: 0 4px 6px -1px rgba(0,0,0,0.02);
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            transition: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .stat-tile:hover { transform: translateY(-5px); box-shadow: 0 20px 25px -5px rgba(0,0,0,0.05); }
        .tile-label { font-size: 0.8rem; font-weight: 700; color: var(--text-dim); text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 10px; }
        .tile-value { font-size: 1.8rem; font-weight: 800; color: var(--text-main); }
        .tile-icon { font-size: 1.5rem; opacity: 0.8; }

        /* Content Hub */
        .workspace-hub {
            background: var(--surface-primary);
            border-radius: 32px;
            border: 1px solid var(--border-subtle);
            box-shadow: 0 10px 30px -10px rgba(0,0,0,0.05);
            overflow: hidden;
        }

        .header-panel {
            padding: 30px;
            background: #fff;
            border-bottom: 1px solid var(--border-subtle);
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }

        .search-wrapper { position: relative; width: 400px; }
        .lux-search {
            height: 52px; border-radius: 16px; border: 2px solid var(--border-subtle);
            padding: 0 20px; padding-<?= $is_ar?'left':'right' ?>: 45px;
            font-size: 0.95rem; font-weight: 500; transition: 0.3s; background: var(--surface-secondary);
        }
        .lux-search:focus { border-color: var(--accent-indigo); background: #fff; outline: none; box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1); }

        /* Modern Table */
        .table thead th {
            background: var(--surface-secondary); color: var(--text-dim); font-size: 0.7rem;
            text-transform: uppercase; padding: 18px 30px; font-weight: 800; border: 0; letter-spacing: 0.08em;
        }
        .table tbody td { padding: 22px 30px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }
        .table tbody tr { transition: background 0.2s ease; }
        .table tbody tr:hover { background: #f8fafc; }

        /* Interactive Elements */
        .edit-trigger {
            font-weight: 800; font-size: 1.1rem; cursor: pointer;
            border-radius: 8px; padding: 4px 8px; transition: 0.2s;
            display: inline-block; min-width: 60px;
        }
        .edit-trigger:hover { background: var(--surface-secondary); color: var(--accent-indigo); }
        .editing-mode { border: 2px solid var(--accent-indigo) !important; background: #fff !important; width: 90px !important; }

        /* Health Visuals */
        .health-indicator { height: 8px; border-radius: 10px; background: #e2e8f0; margin-top: 10px; width: 120px; overflow: hidden; position: relative; }
        .health-fill { height: 100%; transition: width 0.5s ease-out; }

        .btn-hub-action {
            width: 44px; height: 44px; border-radius: 14px; display: inline-flex;
            align-items: center; justify-content: center; background: #fff; border: 1px solid var(--border-subtle);
            color: var(--text-dim); transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .btn-hub-action:hover { transform: translateY(-3px) scale(1.05); color: #fff; border-color: transparent; }
        .act-sell:hover { background: var(--accent-blue); box-shadow: 0 8px 15px rgba(37, 99, 235, 0.2); }
        .act-edit:hover { background: var(--accent-indigo); box-shadow: 0 8px 15px rgba(79, 70, 229, 0.2); }

        .highlight-match { background: #fef08a; padding: 1px 3px; border-radius: 4px; font-weight: bold; }
        
        /* Modal Customization */
        .modal-lux { border-radius: 32px; border: none; overflow: hidden; }
        .lux-input { border-radius: 14px; border: 2px solid var(--border-subtle); padding: 12px 18px; font-weight: 600; }
        .lux-input:focus { border-color: var(--accent-indigo); box-shadow: none; }
    </style>
</head>
<body>

    <nav class="premium-nav shadow-sm">
        <div class="container d-flex justify-content-between align-items-center">
            <div class="d-flex align-items-center gap-2">
                <div style="background: linear-gradient(135deg, var(--accent-blue), var(--accent-indigo)); color: white; padding: 10px; border-radius: 14px;">📦</div>
                <span class="fw-bold fs-5 px-2"><?= $is_ar?'بوابة المخزون المتوفر':'Active Inventory' ?></span>
            </div>
            <div class="d-flex gap-2">
                <a href="index.php" class="btn btn-light rounded-pill px-4 fw-bold border-0"><?= $is_ar?'الرئيسية':'Home' ?></a>
                <button class="btn btn-dark rounded-pill px-4 fw-bold shadow" data-bs-toggle="modal" data-bs-target="#modalAdd">+ <?= $is_ar?'إضافة صنف':'New Item' ?></button>
            </div>
        </div>
    </nav>

    <div class="container py-4">
        <!-- Modern Statistics Board (Active Stock Only) -->
        <div class="dashboard-grid">
            <div class="stat-tile">
                <div class="d-flex justify-content-between">
                    <span class="tile-label"><?= $is_ar?'الأصناف المتوفرة':'Available Items' ?></span>
                    <span class="tile-icon">🏷️</span>
                </div>
                <div class="tile-value"><?= number_format($summary['total_p']) ?></div>
            </div>
            <div class="stat-tile">
                <div class="d-flex justify-content-between">
                    <span class="tile-label"><?= $is_ar?'مجموع القطع':'Total Units' ?></span>
                    <span class="tile-icon">📦</span>
                </div>
                <div class="tile-value"><?= number_format($summary['total_s']) ?></div>
            </div>
            <div class="stat-tile" style="border-left: 4px solid var(--accent-danger);">
                <div class="d-flex justify-content-between">
                    <span class="tile-label"><?= $is_ar?'نواقص (أقل من 5)':'Low Stock Warning' ?></span>
                    <span class="tile-icon">⚠️</span>
                </div>
                <div class="tile-value text-danger"><?= number_format($summary['low_c']) ?></div>
            </div>
            <div class="stat-tile">
                <div class="d-flex justify-content-between">
                    <span class="tile-label"><?= $is_ar?'قيمة المخزن الحالي':'Stock Value' ?></span>
                    <span class="tile-icon">💰</span>
                </div>
                <div class="tile-value"><?= number_format($summary['total_v'], 0) ?></div>
            </div>
        </div>

        <div class="workspace-hub">
            <div class="header-panel">
                <div class="search-wrapper">
                    <input id="searchInput" class="form-control lux-search" placeholder="<?= $is_ar?'ابحث في المتوفر حالياً...':'Search active stock...' ?>">
                    <div id="searchSpinner" class="spinner-border spinner-border-sm text-primary position-absolute" style="display:none; top:20px; <?= $is_ar?'left':'right' ?>:18px;"></div>
                </div>
                <div class="d-flex gap-2">
                    <button class="btn btn-light rounded-pill px-3 fw-bold filter-btn active" data-filter="all"><?= $is_ar?'كل المتوفر':'Show All' ?></button>
                    <button class="btn btn-light rounded-pill px-3 fw-bold filter-btn" data-filter="low"><?= $is_ar?'النواقص فقط':'Low Stock' ?></button>
                    <div class="vr mx-2"></div>
                    <a href="?action=export" class="btn btn-outline-secondary rounded-pill px-4 border-0 fw-bold">Export</a>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th><?= $is_ar?'تفاصيل المنتج':'Product Identity' ?></th>
                            <th class="text-center"><?= $is_ar?'سعر البيع':'Sale Price' ?></th>
                            <th class="text-center"><?= $is_ar?'التكلفة':'Unit Cost' ?></th>
                            <th class="text-center"><?= $is_ar?'المخزون':'Health Status' ?></th>
                            <th class="text-center"><?= $is_ar?'إجراءات':'Actions' ?></th>
                        </tr>
                    </thead>
                    <tbody id="productsTbody">
                        <!-- AJAX content loads here -->
                    </tbody>
                </table>
            </div>

            <div class="p-4 border-top d-flex justify-content-between align-items-center bg-light">
                <div id="resultsInfo" class="small text-muted fw-bold"></div>
                <div class="btn-group shadow-sm rounded-pill overflow-hidden">
                    <button id="prevPage" class="btn btn-white btn-sm px-4 border-end">«</button>
                    <button id="nextPage" class="btn btn-white btn-sm px-4">»</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal: Enhanced Add Product -->
    <div class="modal fade" id="modalAdd" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <form method="post" class="modal-content modal-lux">
                <input type="hidden" name="action" value="add_product">
                <div class="modal-body p-5">
                    <h4 class="fw-bold mb-4"><?= $is_ar?'صنف جديد':'New Product' ?></h4>
                    <div class="mb-3">
                        <label class="small fw-bold text-dim mb-2">PRODUCT NAME</label>
                        <input name="name" class="form-control lux-input" required>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold text-dim mb-2">SKU / SERIAL</label>
                        <input name="sku" class="form-control lux-input">
                    </div>
                    <div class="row g-3 mb-4">
                        <div class="col-4">
                            <label class="small fw-bold text-dim mb-2">COST</label>
                            <input type="number" step="0.01" name="cost" class="form-control lux-input" value="0">
                        </div>
                        <div class="col-4">
                            <label class="small fw-bold text-dim mb-2">PRICE</label>
                            <input type="number" step="0.01" name="price" class="form-control lux-input" value="0">
                        </div>
                        <div class="col-4">
                            <label class="small fw-bold text-dim mb-2">QTY</label>
                            <input type="number" name="stock" class="form-control lux-input" value="0">
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary w-100 py-3 fw-bold rounded-pill shadow-lg">Confirm & Save</button>
                </div>
            </form>
        </div>
    </div>

    <div id="copyToast" style="position:fixed; bottom:30px; left:50%; transform:translateX(-50%); background:var(--text-main); color:#fff; padding:12px 35px; border-radius:50px; font-size:0.9rem; font-weight:700; opacity:0; transition:0.3s; z-index:9999; pointer-events:none; box-shadow: 0 10px 30px rgba(0,0,0,0.3);">Copied!</div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let page = 1;
        let lastQuery = '';
        let currentFilter = 'all';
        let debounceTimer = null;
        const perPage = 40;

        const tbody = document.getElementById('productsTbody');
        const searchInput = document.getElementById('searchInput');

        async function fetchProducts(q = '', p = 1, f = 'all') {
            document.getElementById('searchSpinner').style.display = 'block';
            currentFilter = f;
            try {
                const url = `?ajax=1&q=${encodeURIComponent(q)}&page=${p}&filter=${f}&lang=<?= $lang ?>`;
                const resp = await fetch(url);
                const j = await resp.json();
                if (j.success) {
                    renderRows(j.rows, q);
                    page = j.page;
                    document.getElementById('resultsInfo').textContent = j.total > 0 ? `${j.rows.length} of ${j.total} units` : 'No available stock found';
                    document.getElementById('prevPage').disabled = page <= 1;
                    document.getElementById('nextPage').disabled = (page * perPage) >= j.total;
                }
            } catch (e) { console.error(e); }
            document.getElementById('searchSpinner').style.display = 'none';
        }

        function highlight(text, q) {
            if (!q) return text;
            const regex = new RegExp(`(${q})`, 'gi');
            return text.replace(regex, '<span class="highlight-match">$1</span>');
        }

        function renderRows(rows, q) {
            tbody.innerHTML = rows.map(r => {
                const stock = parseInt(r.stock);
                let color = '#10b981';
                if(stock <= 5) color = '#f43f5e';
                else if(stock <= 20) color = '#f59e0b';
                const progressWidth = Math.min(100, (stock / 50) * 100);

                return `
                    <tr data-id="${r.id}">
                        <td>
                            <div class="fw-bold mb-1 text-dark" style="font-size: 1.05rem;">${highlight(r.name, q)}</div>
                            <div class="d-flex align-items-center gap-2">
                                <span class="badge bg-light text-primary border" style="font-size: 0.75rem; font-weight:700;">ID: #${r.id}</span>
                                <span class="small text-dim">SKU: ${highlight(r.sku || 'N/A', q)}</span>
                                <span class="small text-muted cursor-pointer" onclick="copyToClipboard('${r.sku}')">📋</span>
                            </div>
                        </td>
                        <td class="text-center">
                            <span class="edit-trigger text-primary" data-id="${r.id}" data-field="price">${parseFloat(r.price).toFixed(2)}</span>
                        </td>
                        <td class="text-center">
                            <span class="edit-trigger text-muted" data-id="${r.id}" data-field="cost">${parseFloat(r.cost).toFixed(2)}</span>
                        </td>
                        <td class="text-center">
                            <div class="d-inline-block text-start">
                                <span class="edit-trigger" style="color:${color}" data-id="${r.id}" data-field="stock">${stock}</span>
                                <div class="health-indicator">
                                    <div class="health-fill" style="width:${progressWidth}%; background-color:${color}"></div>
                                </div>
                            </div>
                        </td>
                        <td class="text-center">
                            <a href="sales_create.php?add_product=${r.id}" class="btn-hub-action act-sell" title="Quick Sale">🛒</a>
                            <a href="edit_product.php?id=${r.id}" class="btn-hub-action act-edit">✏️</a>
                        </td>
                    </tr>
                `;
            }).join('');
            attachEditEvents();
        }

        function attachEditEvents() {
            document.querySelectorAll('.edit-trigger').forEach(el => {
                el.onclick = function() {
                    const id = this.dataset.id;
                    const field = this.dataset.field;
                    const oldVal = this.textContent;
                    const input = document.createElement('input');
                    input.type = 'number';
                    input.value = oldVal;
                    input.className = 'form-control editing-mode';
                    this.replaceWith(input);
                    input.focus();
                    input.onblur = () => finishEdit(input, id, field, oldVal);
                    input.onkeydown = (e) => { if(e.key === 'Enter') input.blur(); };
                };
            });
        }

        async function finishEdit(input, id, field, oldVal) {
            const newVal = input.value;
            const span = document.createElement('span');
            span.className = 'edit-trigger';
            span.dataset.id = id; span.dataset.field = field;
            span.textContent = newVal;

            if (newVal !== oldVal) {
                const fd = new FormData();
                fd.append('id', id); fd.append('field', field); fd.append('value', newVal);
                await fetch('?update_field=1', { method: 'POST', body: fd });
                fetchProducts(lastQuery, page, currentFilter);
            }
            input.replaceWith(span);
            attachEditEvents();
        }

        function copyToClipboard(text) {
            if(!text || text === 'null') return;
            navigator.clipboard.writeText(text);
            const t = document.getElementById('copyToast');
            t.style.opacity = '1'; setTimeout(() => t.style.opacity = '0', 1500);
        }

        searchInput.oninput = () => {
            clearTimeout(debounceTimer);
            debounceTimer = setTimeout(() => { lastQuery = searchInput.value; fetchProducts(lastQuery, 1, currentFilter); }, 300);
        };

        document.querySelectorAll('.filter-btn').forEach(btn => {
            btn.onclick = () => {
                document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active', 'btn-dark', 'text-white'));
                btn.classList.add('active');
                fetchProducts(lastQuery, 1, btn.dataset.filter);
            };
        });

        document.getElementById('prevPage').onclick = () => fetchProducts(lastQuery, page - 1, currentFilter);
        document.getElementById('nextPage').onclick = () => fetchProducts(lastQuery, page + 1, currentFilter);

        fetchProducts('', 1, 'all');
    </script>
</body>
</html>