<?php
// المسار: admin/products.php

declare(strict_types=1);

require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/db.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    ini_set('session.use_strict_mode', '1');
    session_start();
}

if (empty($_SESSION['admin'])) {
    header('Location: login.php');
    exit;
}

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

$statusMsg = '';
$statusClass = 'alert-info';
if (isset($_GET['status'])) {
    $map = [
        'deleted' => ['تم حذف المنتج بنجاح.', 'alert-success'],
        'error' => ['حدث خطأ أثناء الحذف.', 'alert-danger'],
        'not_found' => ['المنتج غير موجود.', 'alert-warning'],
        'csrf_fail' => ['فشل التحقق الأمني.', 'alert-danger'],
        'bad_id' => ['معرّف المنتج غير صالح.', 'alert-warning'],
        'invalid_method' => ['طريقة غير مسموحة.', 'alert-warning'],
    ];
    if (isset($map[$_GET['status']])) {
        [$statusMsg, $statusClass] = $map[$_GET['status']];
    }
}

$q = trim($_GET['q'] ?? '');
$categoryFilter = (int)($_GET['category_id'] ?? 0);
$featuredFilter = trim($_GET['featured'] ?? '');

$cats = [];
try {
    $cats = $pdo->query('SELECT id,name FROM categories ORDER BY name')->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $cats = [];
}

$where = [];
$params = [];

if ($q !== '') {
    $where[] = '(p.name LIKE :q OR p.slug LIKE :q OR p.description LIKE :q)';
    $params[':q'] = '%'.$q.'%';
}
if ($categoryFilter > 0) {
    $where[] = 'p.category_id = :cat';
    $params[':cat'] = $categoryFilter;
}
if ($featuredFilter === '1' || $featuredFilter === '0') {
    $where[] = 'p.is_featured = :featured';
    $params[':featured'] = (int)$featuredFilter;
}

$sql = "SELECT p.*, c.name AS category_name
        FROM products p
        LEFT JOIN categories c ON p.category_id = c.id";
if ($where) {
    $sql .= ' WHERE '.implode(' AND ', $where);
}
$sql .= ' ORDER BY p.id DESC';

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

$totalProducts = count($products);
$featuredCount = 0;
$totalStock = 0;
foreach ($products as $p) {
    if (!empty($p['is_featured'])) $featuredCount++;
    $totalStock += (int)($p['stock'] ?? 0);
}

function product_image_url(array $p): string {
    $img = trim((string)($p['main_image'] ?? ''));
    if ($img === '') return '';
    if (preg_match('~^https?://~i', $img)) return $img;
    return '../'.ltrim($img, '/');
}

$title = 'إدارة المنتجات';
?>
<!doctype html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <title><?= e($title) ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root{
            --bg:#f4f7fb;
            --card:#ffffff;
            --text:#0f172a;
            --muted:#64748b;
            --line:#e2e8f0;
            --green:#15803d;
            --blue:#2563eb;
            --gold:#f59e0b;
            --danger:#dc2626;
            --shadow:0 18px 45px rgba(15,23,42,.08);
            --radius:22px;
        }
        *{box-sizing:border-box}
        html{scroll-behavior:smooth}
        body{
            margin:0;
            min-height:100vh;
            font-family:Tahoma, Arial, sans-serif;
            background:
                radial-gradient(circle at top right, rgba(21,128,61,.13), transparent 34%),
                radial-gradient(circle at bottom left, rgba(37,99,235,.12), transparent 36%),
                var(--bg);
            color:var(--text);
        }
        .page-shell{width:min(1320px,100%);margin:auto;padding:22px 14px 34px}
        .hero{
            background:linear-gradient(135deg,#0f766e,#15803d 54%,#2563eb);
            border-radius:28px;
            color:#fff;
            padding:24px;
            box-shadow:var(--shadow);
            position:relative;
            overflow:hidden;
            margin-bottom:18px;
        }
        .hero:before{content:"";position:absolute;inset:-80px auto auto -70px;width:220px;height:220px;border-radius:50%;background:rgba(255,255,255,.16)}
        .hero-inner{position:relative;z-index:1;display:flex;gap:18px;align-items:center;justify-content:space-between;flex-wrap:wrap}
        .hero h1{font-size:clamp(26px,4vw,40px);font-weight:900;margin:0 0 6px}
        .hero p{margin:0;color:rgba(255,255,255,.86);font-size:15px}
        .hero-actions{display:flex;gap:10px;flex-wrap:wrap}
        .btn-soft-light{background:rgba(255,255,255,.16);border:1px solid rgba(255,255,255,.34);color:#fff;border-radius:999px;padding:10px 16px;font-weight:800;text-decoration:none;transition:.18s}
        .btn-soft-light:hover{background:#fff;color:#0f766e;transform:translateY(-1px)}
        .btn-main{background:#fff;color:#15803d;border:0;border-radius:999px;padding:10px 16px;font-weight:900;text-decoration:none;box-shadow:0 10px 24px rgba(0,0,0,.12)}
        .btn-main:hover{color:#166534;transform:translateY(-1px)}
        .stats-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-bottom:18px}
        .stat-card{background:rgba(255,255,255,.9);border:1px solid rgba(226,232,240,.9);border-radius:20px;padding:16px;box-shadow:0 10px 28px rgba(15,23,42,.06)}
        .stat-card .num{font-size:26px;font-weight:900;line-height:1;color:#0f172a}
        .stat-card .label{color:var(--muted);font-size:13px;margin-top:6px;font-weight:700}
        .panel{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);box-shadow:var(--shadow);padding:16px;margin-bottom:18px}
        .filters{display:grid;grid-template-columns:2fr 1.2fr 1fr auto;gap:10px;align-items:end}
        .form-control,.form-select{border-radius:14px;min-height:44px;border-color:#cbd5e1}
        .form-control:focus,.form-select:focus{border-color:#15803d;box-shadow:0 0 0 .2rem rgba(21,128,61,.13)}
        .btn-pill{border-radius:999px;font-weight:800;min-height:42px;display:inline-flex;align-items:center;justify-content:center;gap:6px}
        .desktop-table{display:block}
        .mobile-cards{display:none}
        .table-wrap{border-radius:18px;overflow:hidden;border:1px solid var(--line)}
        table{margin:0!important;min-width:850px;background:#fff}
        thead th{background:#f8fafc!important;color:#334155!important;font-size:13px;border-bottom:1px solid var(--line)!important;white-space:nowrap}
        tbody td{vertical-align:middle;border-color:#edf2f7!important}
        tbody tr:hover{background:#f8fafc}
        .prod-cell{display:flex;align-items:center;gap:10px;min-width:260px}
        .prod-thumb{width:54px;height:54px;border-radius:14px;object-fit:cover;border:1px solid var(--line);background:#eef2f7;flex:0 0 auto}
        .prod-thumb.placeholder{display:flex;align-items:center;justify-content:center;color:#94a3b8;font-size:22px}
        .prod-title{font-weight:900;color:#0f172a;line-height:1.4}
        .prod-sub{font-size:12px;color:#94a3b8;direction:ltr;text-align:right;max-width:220px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
        .badge-featured{background:var(--gold);color:#111827}
        .action-group{display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap}
        .empty-state{text-align:center;padding:42px 14px;color:#64748b}
        .empty-state i{font-size:46px;color:#cbd5e1;margin-bottom:8px;display:block}
        .product-card{background:#fff;border:1px solid var(--line);border-radius:20px;padding:13px;box-shadow:0 10px 26px rgba(15,23,42,.06);margin-bottom:12px}
        .product-card-head{display:flex;gap:12px;align-items:flex-start}
        .product-card .prod-thumb{width:76px;height:76px;border-radius:18px}
        .card-info{min-width:0;flex:1}
        .meta-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;margin:12px 0}
        .meta{background:#f8fafc;border:1px solid #edf2f7;border-radius:14px;padding:9px}
        .meta span{display:block;color:#64748b;font-size:12px;font-weight:700}
        .meta b{display:block;font-size:15px;margin-top:2px;color:#0f172a}
        .card-actions{display:grid;grid-template-columns:1fr 1fr;gap:8px}
        .card-actions .btn{width:100%}
        .back-row{display:flex;justify-content:center;margin-top:18px}
        @media (max-width: 900px){
            .filters{grid-template-columns:1fr 1fr}
            .filters .full-mobile{grid-column:1/-1}
            .stats-grid{grid-template-columns:repeat(3,1fr)}
        }
        @media (max-width: 768px){
            .page-shell{padding:12px 10px 28px}
            .hero{border-radius:22px;padding:18px;margin-bottom:12px}
            .hero-inner{align-items:flex-start}
            .hero-actions{width:100%;display:grid;grid-template-columns:1fr 1fr}
            .hero-actions a{width:100%;text-align:center;justify-content:center}
            .stats-grid{grid-template-columns:1fr 1fr 1fr;gap:8px}
            .stat-card{padding:12px;border-radius:16px;text-align:center}
            .stat-card .num{font-size:21px}
            .stat-card .label{font-size:11px}
            .panel{padding:12px;border-radius:18px}
            .filters{grid-template-columns:1fr}
            .desktop-table{display:none}
            .mobile-cards{display:block}
            .back-row .btn{width:100%}
        }
        @media (max-width: 420px){
            .hero-actions{grid-template-columns:1fr}
            .stats-grid{grid-template-columns:1fr}
            .meta-grid{grid-template-columns:1fr}
            .card-actions{grid-template-columns:1fr}
            .product-card-head{gap:10px}
            .product-card .prod-thumb{width:64px;height:64px}
        }
        @media (min-width: 1200px){.page-shell{padding-top:28px}.panel{padding:20px}}
    </style>
</head>
<body>
<div class="page-shell">
    <section class="hero">
        <div class="hero-inner">
            <div>
                <h1><i class="bi bi-box-seam"></i> <?= e($title) ?></h1>
                <p>واجهة محسّنة تعمل بوضوح على الموبايل، التابلت، والكمبيوتر.</p>
            </div>
            <div class="hero-actions">
                <a href="product_add.php" class="btn-main"><i class="bi bi-plus-lg"></i> منتج جديد</a>
                <a href="categories.php" class="btn-soft-light"><i class="bi bi-tags"></i> الأقسام</a>
            </div>
        </div>
    </section>

    <?php if ($statusMsg): ?>
        <div class="alert <?= e($statusClass) ?> rounded-4 shadow-sm"><?= e($statusMsg) ?></div>
    <?php endif; ?>

    <div class="stats-grid">
        <div class="stat-card"><div class="num"><?= (int)$totalProducts ?></div><div class="label">إجمالي المنتجات</div></div>
        <div class="stat-card"><div class="num"><?= (int)$featuredCount ?></div><div class="label">منتجات مميزة</div></div>
        <div class="stat-card"><div class="num"><?= (int)$totalStock ?></div><div class="label">إجمالي المخزون</div></div>
    </div>

    <form method="get" class="panel filters">
        <div class="full-mobile">
            <label class="form-label fw-bold">بحث سريع</label>
            <input type="search" name="q" class="form-control" value="<?= e($q) ?>" placeholder="ابحث باسم المنتج أو السلاگ أو الوصف...">
        </div>
        <div>
            <label class="form-label fw-bold">القسم</label>
            <select name="category_id" class="form-select">
                <option value="0">كل الأقسام</option>
                <?php foreach ($cats as $c): ?>
                    <option value="<?= (int)$c['id'] ?>" <?= $categoryFilter === (int)$c['id'] ? 'selected' : '' ?>><?= e($c['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
        <div>
            <label class="form-label fw-bold">التمييز</label>
            <select name="featured" class="form-select">
                <option value="" <?= $featuredFilter === '' ? 'selected' : '' ?>>الكل</option>
                <option value="1" <?= $featuredFilter === '1' ? 'selected' : '' ?>>مميز فقط</option>
                <option value="0" <?= $featuredFilter === '0' ? 'selected' : '' ?>>غير مميز</option>
            </select>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <button class="btn btn-success btn-pill"><i class="bi bi-search"></i> بحث</button>
            <a href="products.php" class="btn btn-outline-secondary btn-pill"><i class="bi bi-arrow-clockwise"></i> تصفير</a>
        </div>
    </form>

    <section class="panel desktop-table">
        <div class="d-flex align-items-center justify-content-between flex-wrap gap-2 mb-3">
            <h2 class="h6 m-0 fw-bold"><i class="bi bi-list-ul"></i> قائمة المنتجات</h2>
            <small class="text-muted">عدد النتائج: <?= (int)$totalProducts ?></small>
        </div>
        <?php if ($products): ?>
            <div class="table-responsive table-wrap">
                <table class="table table-hover align-middle">
                    <thead>
                    <tr>
                        <th>#</th>
                        <th>المنتج</th>
                        <th>القسم</th>
                        <th>السعر</th>
                        <th>المخزون</th>
                        <th>مميز؟</th>
                        <th class="text-end">إجراءات</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($products as $p): $img = product_image_url($p); ?>
                        <tr>
                            <td class="fw-bold text-muted"><?= (int)$p['id'] ?></td>
                            <td>
                                <div class="prod-cell">
                                    <?php if ($img): ?>
                                        <img src="<?= e($img) ?>" class="prod-thumb" alt="">
                                    <?php else: ?>
                                        <div class="prod-thumb placeholder"><i class="bi bi-image"></i></div>
                                    <?php endif; ?>
                                    <div>
                                        <div class="prod-title"><?= e($p['name']) ?></div>
                                        <div class="prod-sub"><?= e($p['slug'] ?? '') ?></div>
                                    </div>
                                </div>
                            </td>
                            <td><?= e($p['category_name'] ?? 'غير مصنف') ?></td>
                            <td class="fw-bold"><?= number_format((float)$p['price'], 2) ?></td>
                            <td><span class="badge text-bg-light border"><?= (int)$p['stock'] ?></span></td>
                            <td>
                                <?php if (!empty($p['is_featured'])): ?>
                                    <span class="badge badge-featured">مميز</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">—</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="action-group">
                                    <a href="product_edit.php?id=<?= (int)$p['id'] ?>" class="btn btn-sm btn-outline-primary rounded-pill"><i class="bi bi-pencil-square"></i> تعديل</a>
                                    <form method="post" action="product_delete.php" class="d-inline" onsubmit="return confirm('هل أنت متأكد من حذف المنتج؟ هذا الإجراء لا يمكن التراجع عنه');">
                                        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                                        <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                                        <button class="btn btn-sm btn-outline-danger rounded-pill"><i class="bi bi-trash"></i> حذف</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div class="empty-state"><i class="bi bi-inboxes"></i><div class="fw-bold">لا توجد منتجات مطابقة.</div></div>
        <?php endif; ?>
    </section>

    <section class="mobile-cards">
        <?php if ($products): ?>
            <?php foreach ($products as $p): $img = product_image_url($p); ?>
                <article class="product-card">
                    <div class="product-card-head">
                        <?php if ($img): ?>
                            <img src="<?= e($img) ?>" class="prod-thumb" alt="">
                        <?php else: ?>
                            <div class="prod-thumb placeholder"><i class="bi bi-image"></i></div>
                        <?php endif; ?>
                        <div class="card-info">
                            <div class="d-flex align-items-center justify-content-between gap-2">
                                <span class="badge text-bg-light border">#<?= (int)$p['id'] ?></span>
                                <?php if (!empty($p['is_featured'])): ?><span class="badge badge-featured">مميز</span><?php endif; ?>
                            </div>
                            <div class="prod-title mt-2"><?= e($p['name']) ?></div>
                            <div class="prod-sub"><?= e($p['slug'] ?? '') ?></div>
                        </div>
                    </div>
                    <div class="meta-grid">
                        <div class="meta"><span>القسم</span><b><?= e($p['category_name'] ?? 'غير مصنف') ?></b></div>
                        <div class="meta"><span>السعر</span><b><?= number_format((float)$p['price'], 2) ?></b></div>
                        <div class="meta"><span>المخزون</span><b><?= (int)$p['stock'] ?></b></div>
                        <div class="meta"><span>الحالة</span><b><?= !empty($p['is_featured']) ? 'مميز' : 'عادي' ?></b></div>
                    </div>
                    <div class="card-actions">
                        <a href="product_edit.php?id=<?= (int)$p['id'] ?>" class="btn btn-outline-primary rounded-pill"><i class="bi bi-pencil-square"></i> تعديل</a>
                        <form method="post" action="product_delete.php" onsubmit="return confirm('هل أنت متأكد من حذف المنتج؟ هذا الإجراء لا يمكن التراجع عنه');">
                            <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
                            <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                            <button class="btn btn-outline-danger rounded-pill"><i class="bi bi-trash"></i> حذف</button>
                        </form>
                    </div>
                </article>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="panel empty-state"><i class="bi bi-inboxes"></i><div class="fw-bold">لا توجد منتجات مطابقة.</div></div>
        <?php endif; ?>
    </section>

    <div class="back-row">
        <a href="dashboard.php" class="btn btn-secondary btn-pill px-4"><i class="bi bi-arrow-left"></i> عودة للوحة التحكم</a>
    </div>
</div>
</body>
</html>
