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

// 1. التعديل: اللغة الافتراضية الآن إنجليزية
$lang = $_GET['lang'] ?? 'en';
$is_ar = $lang === 'ar';

$L = [
    'en' => [
        'title' => 'Stock Audit Report',
        'subtitle' => 'Monitor and manage your inventory levels efficiently.',
        'category' => 'Category',
        'filter' => 'Inventory Status',
        'out' => 'Out of Stock',
        'low' => 'Low Stock Alert',
        'all' => 'All Inventory',
        'search' => 'Search by name or SKU...',
        'sku' => 'SKU',
        'name' => 'Product Name',
        'stock' => 'Qty',
        'cost' => 'Unit Cost',
        'price' => 'Selling Price',
        'category_name' => 'Category',
        'home' => 'Dashboard',
        'print' => 'Print Report',
        'export' => 'Export CSV',
        'no_data' => 'No products match your criteria.',
        'stats_out' => 'Out of Stock Items',
        'stats_low' => 'Low Stock Items',
        'currency' => '$',
        'all_cats' => 'All Categories'
    ],
    'ar' => [
        'title' => 'تقرير جرد المخزون',
        'subtitle' => 'مراقبة وإدارة مستويات المخزون الخاص بك بكفاءة.',
        'category' => 'التصنيف',
        'filter' => 'حالة المخزون',
        'out' => 'منتجات نفدت',
        'low' => 'توشك على النفاد',
        'all' => 'كافة المنتجات',
        'search' => 'بحث بالاسم أو الكود...',
        'sku' => 'الرمز',
        'name' => 'اسم المنتج',
        'stock' => 'الكمية',
        'cost' => 'التكلفة',
        'price' => 'السعر',
        'category_name' => 'القسم',
        'home' => 'الرئيسية',
        'print' => 'طباعة',
        'export' => 'تصدير CSV',
        'no_data' => 'لا توجد نتائج مطابقة لبحثك.',
        'stats_out' => 'أصناف نفدت',
        'stats_low' => 'أصناف شارفت على النفاد',
        'currency' => 'ر.س',
        'all_cats' => 'كافة الأصناف'
    ]
];

// 2. جلب التصنيفات والتأكد من وجود الجدول
$categories = [];
try {
    $hasCategoriesTable = $pdo->query("SHOW TABLES LIKE 'categories'")->fetchColumn();
    if ($hasCategoriesTable) {
        $categories = $pdo->query("SELECT id, name FROM categories ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    // اختياري: سجل الخطأ هنا
}

// 3. منطق الفلترة
$filter = $_GET['stock_filter'] ?? 'all';
$cat_id = !empty($_GET['category_id']) ? intval($_GET['category_id']) : null;

$where = "1";
if ($filter === 'low') {
    $where = "p.stock > 0 AND p.stock < 5";
} elseif ($filter === 'out') {
    $where = "p.stock <= 0";
}

if ($cat_id) {
    $where .= " AND p.category_id = $cat_id";
}

// 4. جلب المنتجات مع الربط مع جدول الأصناف
$products = [];
try {
    $sql = "SELECT p.id, p.sku, 
            COALESCE(NULLIF(p.name_en,''), p.name_ar, 'Unnamed') AS name, 
            p.stock, p.cost, p.price";
    
    if (!empty($categories)) {
        $sql .= ", c.name AS category_name";
    }
    
    $sql .= " FROM products p";
    
    if (!empty($categories)) {
        $sql .= " LEFT JOIN categories c ON c.id = p.category_id";
    }
    
    $sql .= " WHERE $where ORDER BY p.stock ASC";
    $products = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // في حال حدوث خطأ في الاستعلام
    $error_msg = $e->getMessage();
}
?>
<!doctype html>
<html lang="<?= $lang ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $L[$lang]['title'] ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    
    <style>
        :root {
            --primary-color: #4361ee;
            --bg-color: #f8f9fc;
            --card-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            --border-radius: 12px;
        }

        body { 
            background: var(--bg-color); 
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Inter', sans-serif" ?>;
            color: #334155;
            padding-bottom: 50px;
        }

        .navbar-top {
            background: #fff;
            padding: 1rem 0;
            border-bottom: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }

        .header-section { margin-bottom: 2rem; }
        .page-title { font-weight: 700; color: #1e293b; margin: 0; }

        .card {
            border: none;
            border-radius: var(--border-radius);
            box-shadow: var(--card-shadow);
            overflow: hidden;
            background: #fff;
            margin-bottom: 1.5rem;
        }

        .filter-bar {
            background: #fff;
            padding: 1.25rem;
            border-radius: var(--border-radius);
            box-shadow: var(--card-shadow);
            margin-bottom: 1.5rem;
        }

        .table thead th {
            background: #f1f5f9;
            text-transform: uppercase;
            font-size: 0.75rem;
            color: #64748b;
            padding: 1rem;
            border: none;
        }

        .table tbody td { padding: 1rem; vertical-align: middle; border-color: #f1f5f9; }

        .stock-badge {
            padding: 0.35em 0.65em;
            font-size: 0.85em;
            font-weight: 600;
            border-radius: 6px;
        }

        .btn { border-radius: 8px; font-weight: 500; transition: all 0.2s; }
        .search-container { position: relative; }
        .search-container .bi-search {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            <?= $is_ar ? 'left: 15px;' : 'right: 15px;' ?>
            color: #94a3b8;
        }
        
        @media print {
            .navbar-top, .filter-bar, .actions-bar, .no-print, .no-results-icon { display: none !important; }
            body { background: white; padding: 0; }
            .card { box-shadow: none; border: 1px solid #eee; }
        }
    </style>
</head>
<body>

<nav class="navbar-top no-print">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="index.php" class="btn btn-outline-dark btn-sm d-flex align-items-center gap-2">
            <i class="bi bi-arrow-<?= $is_ar ? 'right' : 'left' ?>"></i> <?= $L[$lang]['home'] ?>
        </a>
        <div class="d-flex gap-2">
            <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="btn btn-light btn-sm fw-bold border">
                <?= $is_ar ? 'English' : 'العربية' ?>
            </a>
        </div>
    </div>
</nav>

<div class="container">
    
    <div class="header-section d-md-flex justify-content-between align-items-end">
        <div>
            <h2 class="page-title"><?= $L[$lang]['title'] ?></h2>
            <p class="text-muted mb-0"><?= $L[$lang]['subtitle'] ?></p>
        </div>
        <div class="actions-bar mt-3 mt-md-0 d-flex gap-2">
            <button onclick="window.print()" class="btn btn-outline-primary d-flex align-items-center gap-2">
                <i class="bi bi-printer"></i> <?= $L[$lang]['print'] ?>
            </button>
            <a href="export_stock.php?stock_filter=<?= urlencode($filter) ?>&category_id=<?= $cat_id ?>&lang=<?= $lang ?>" class="btn btn-success d-flex align-items-center gap-2">
                <i class="bi bi-file-earmark-spreadsheet"></i> <?= $L[$lang]['export'] ?>
            </a>
        </div>
    </div>

    <!-- Filters -->
    <div class="filter-bar no-print">
        <form method="get" class="row g-3">
            <input type="hidden" name="lang" value="<?= $lang ?>">
            
            <div class="col-md-3">
                <label class="form-label small fw-bold"><?= $L[$lang]['filter'] ?></label>
                <select name="stock_filter" class="form-select shadow-sm" onchange="this.form.submit()">
                    <option value="all" <?= $filter=='all'?'selected':'' ?>><?= $L[$lang]['all'] ?></option>
                    <option value="out" <?= $filter=='out'?'selected':'' ?>><?= $L[$lang]['out'] ?></option>
                    <option value="low" <?= $filter=='low'?'selected':'' ?>><?= $L[$lang]['low'] ?></option>
                </select>
            </div>

            <?php if(!empty($categories)): ?>
            <div class="col-md-3">
                <label class="form-label small fw-bold"><?= $L[$lang]['category'] ?></label>
                <select name="category_id" class="form-select shadow-sm" onchange="this.form.submit()">
                    <option value=""><?= $L[$lang]['all_cats'] ?></option>
                    <?php foreach($categories as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= $cat_id == $c['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['name']) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>

            <div class="col-md-6">
                <label class="form-label small fw-bold"><?= $L[$lang]['search'] ?></label>
                <div class="search-container">
                    <input type="text" id="search" class="form-control shadow-sm" placeholder="<?= $L[$lang]['search'] ?>">
                    <i class="bi bi-search"></i>
                </div>
            </div>
        </form>
    </div>

    <?php if(isset($error_msg)): ?>
        <div class="alert alert-danger">⚠️ Error: <?= htmlspecialchars($error_msg) ?></div>
    <?php endif; ?>

    <!-- Table Card -->
    <div class="card border-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th class="text-center">#</th>
                        <th><?= $L[$lang]['sku'] ?></th>
                        <th><?= $L[$lang]['name'] ?></th>
                        <?php if(!empty($categories)): ?><th><?= $L[$lang]['category_name'] ?></th><?php endif; ?>
                        <th class="text-center"><?= $L[$lang]['stock'] ?></th>
                        <th><?= $L[$lang]['cost'] ?></th>
                        <th><?= $L[$lang]['price'] ?></th>
                    </tr>
                </thead>
                <tbody id="productTable">
                <?php if(empty($products)): ?>
                    <tr>
                        <td colspan="<?= !empty($categories) ? 7 : 6 ?>" class="text-center py-5">
                            <i class="bi bi-inbox text-muted display-4 no-results-icon"></i>
                            <p class="text-muted mt-2"><?= $L[$lang]['no_data'] ?></p>
                        </td>
                    </tr>
                <?php else: $i=1; foreach($products as $p): 
                    $status_class = ($p['stock'] <= 0) ? 'bg-danger-subtle text-danger' : (($p['stock'] < 5) ? 'bg-warning-subtle text-warning' : 'bg-success-subtle text-success');
                ?>
                    <tr>
                        <td class="text-center text-muted small"><?= $i++ ?></td>
                        <td><code class="fw-bold text-dark"><?= htmlspecialchars($p['sku']) ?></code></td>
                        <td class="fw-semibold"><?= htmlspecialchars($p['name']) ?></td>
                        <?php if(!empty($categories)): ?>
                            <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($p['category_name'] ?? '-') ?></span></td>
                        <?php endif; ?>
                        <td class="text-center">
                            <span class="stock-badge <?= $status_class ?>">
                                <?= htmlspecialchars($p['stock']) ?>
                            </span>
                        </td>
                        <td class="text-secondary"><?= number_format($p['cost'], 2) ?> <small><?= $L[$lang]['currency'] ?></small></td>
                        <td class="fw-bold text-primary"><?= number_format($p['price'], 2) ?> <small><?= $L[$lang]['currency'] ?></small></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.getElementById('search').addEventListener('input', function(){
    const term = this.value.toLowerCase().trim();
    const rows = document.querySelectorAll('#productTable tr');
    rows.forEach(tr => {
        if (tr.innerText.toLowerCase().includes(term)) {
            tr.style.setProperty('display', '', 'important');
        } else {
            tr.style.setProperty('display', 'none', 'important');
        }
    });
});
</script>
</body>
</html>