<?php
require_once '../includes/auth.php';
require_once '../includes/config.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$keyword = trim($_GET['keyword'] ?? '');
$status  = $_GET['status'] ?? '';

$where = " WHERE 1 ";
if ($keyword !== '') {
    $keywordEsc = $conn->real_escape_string($keyword);
    $where .= " AND (b.name LIKE '%{$keywordEsc}%' OR b.slug LIKE '%{$keywordEsc}%') ";
}
if ($status !== '' && ($status === '0' || $status === '1')) {
    $where .= " AND b.status = " . (int)$status;
}

$sql = "
    SELECT 
        b.*,
        (
            SELECT COUNT(*)
            FROM products p
            WHERE p.brand_part = b.name
        ) AS products_count
    FROM brands b
    {$where}
    ORDER BY b.sort_order ASC, b.id DESC
";
$result = $conn->query($sql);

$totalBrands = 0;
$activeBrands = 0;
$inactiveBrands = 0;
$totalLinkedProducts = 0;

$r = $conn->query("SELECT COUNT(*) AS c FROM brands");
if ($r) $totalBrands = (int)$r->fetch_assoc()['c'];
$r = $conn->query("SELECT COUNT(*) AS c FROM brands WHERE status = 1");
if ($r) $activeBrands = (int)$r->fetch_assoc()['c'];
$r = $conn->query("SELECT COUNT(*) AS c FROM brands WHERE status = 0");
if ($r) $inactiveBrands = (int)$r->fetch_assoc()['c'];
$r = $conn->query("SELECT COUNT(*) AS c FROM products WHERE brand_part IS NOT NULL AND brand_part != ''");
if ($r) $totalLinkedProducts = (int)$r->fetch_assoc()['c'];
?>

<style>
:root{
    --nay:#96b8cc;
    --nay-dark:#183153;
    --nay-soft:#eef6fa;
    --text:#0f172a;
    --muted:#64748b;
    --line:#e2e8f0;
    --bg:#f8fbfd;
    --white:#ffffff;
    --success-bg:#dcfce7;
    --success:#166534;
    --danger-bg:#fee2e2;
    --danger:#991b1b;
}
.page-wrap{padding:22px;direction:rtl;background:var(--bg)}
.hero-card{background:linear-gradient(135deg,#183153 0%,#27496a 45%,#96b8cc 100%);border-radius:26px;padding:26px;box-shadow:0 18px 40px rgba(24,49,83,.18);color:#fff;margin-bottom:20px;display:flex;justify-content:space-between;gap:18px;align-items:flex-start;flex-wrap:wrap}
.hero-title h1{margin:0;font-size:31px;font-weight:900;letter-spacing:-.3px}.hero-title p{margin:10px 0 0;color:rgba(255,255,255,.88);font-size:15px;line-height:1.8;max-width:700px}
.hero-actions{display:flex;gap:10px;flex-wrap:wrap}.hero-btn,.ghost-btn,.filter-btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:13px 18px;border-radius:14px;text-decoration:none;border:none;font-weight:800;cursor:pointer;transition:.18s ease}
.hero-btn{background:#fff;color:var(--nay-dark)}.hero-btn:hover,.ghost-btn:hover,.filter-btn:hover{transform:translateY(-1px)}
.ghost-btn{background:rgba(255,255,255,.16);color:#fff;border:1px solid rgba(255,255,255,.18)}
.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;margin-bottom:20px}
.stat-card{position:relative;background:var(--white);border:1px solid #edf2f7;border-radius:24px;padding:18px 18px 20px;box-shadow:0 12px 28px rgba(15,23,42,.06);overflow:hidden}
.stat-card:before{content:'';position:absolute;top:0;right:0;width:84px;height:84px;background:radial-gradient(circle,var(--nay-soft),transparent 70%)}
.stat-label{font-size:13px;font-weight:800;color:var(--muted);margin-bottom:10px}.stat-value{font-size:32px;font-weight:900;color:var(--text);line-height:1}.stat-note{margin-top:10px;color:var(--muted);font-size:12px}
.panel{background:var(--white);border:1px solid #edf2f7;border-radius:24px;box-shadow:0 12px 28px rgba(15,23,42,.06);overflow:hidden}
.panel-head{padding:18px 20px;border-bottom:1px solid #f1f5f9;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;background:linear-gradient(180deg,#fff,#fbfdff)}
.panel-head h2{margin:0;color:var(--nay-dark);font-size:21px;font-weight:900}.panel-head p{margin:6px 0 0;color:var(--muted);font-size:13px}
.filters{padding:18px 20px;display:grid;grid-template-columns:2fr 1fr auto auto;gap:12px;border-bottom:1px solid #f1f5f9;background:#fcfeff}
.input,.select{width:100%;height:48px;padding:0 14px;border:1px solid var(--line);border-radius:14px;background:#fff;font-size:15px;outline:none;transition:.15s ease;box-sizing:border-box}
.input:focus,.select:focus{border-color:var(--nay);box-shadow:0 0 0 4px rgba(150,184,204,.18)}
.filter-btn{background:var(--nay-dark);color:#fff;min-width:132px}.filter-reset{background:var(--nay-soft);color:var(--nay-dark)}
.table-wrap{overflow:auto}.table{width:100%;border-collapse:separate;border-spacing:0;min-width:1060px}
.table thead th{position:sticky;top:0;background:#f8fbfe;color:#475569;font-size:13px;font-weight:900;padding:15px 12px;border-bottom:1px solid #eaf0f5;text-align:center;white-space:nowrap}
.table tbody td{padding:14px 12px;border-bottom:1px solid #f1f5f9;text-align:center;vertical-align:middle;color:#1e293b}
.table tbody tr:hover{background:#fbfeff}
.brand-cell{display:flex;align-items:center;gap:12px;justify-content:flex-start;text-align:right;min-width:240px}
.brand-thumb{width:56px;height:56px;border-radius:18px;background:#f1f5f9;object-fit:cover;border:1px solid #e2e8f0;flex:0 0 auto}.brand-thumb.placeholder{display:flex;align-items:center;justify-content:center;font-weight:900;color:#6b7280;background:linear-gradient(135deg,#eef6fa,#f8fbfd)}
.brand-name{font-weight:900;color:var(--text);font-size:15px}.brand-desc{font-size:12px;color:var(--muted);margin-top:5px;max-width:320px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.slug-chip,.count-chip{display:inline-flex;align-items:center;justify-content:center;padding:8px 12px;border-radius:999px;font-size:12px;font-weight:800;background:#f8fafc;color:#475569;border:1px solid #e2e8f0}
.status-badge{display:inline-flex;padding:8px 12px;border-radius:999px;font-size:12px;font-weight:900}
.status-on{background:var(--success-bg);color:var(--success)}.status-off{background:var(--danger-bg);color:var(--danger)}
.action-group{display:flex;gap:8px;justify-content:center;flex-wrap:wrap}.btn-sm{padding:10px 12px;border-radius:12px;text-decoration:none;font-size:13px;font-weight:900;display:inline-flex;align-items:center;justify-content:center;min-width:68px;transition:.15s ease}.btn-sm:hover{transform:translateY(-1px)}.btn-edit{background:#eff6ff;color:#1d4ed8}.btn-delete{background:#fef2f2;color:#dc2626}
.alert{margin-bottom:18px;padding:14px 16px;border-radius:16px;font-weight:800;border:1px solid transparent}.alert-success{background:#ecfdf5;color:#065f46;border-color:#a7f3d0}.alert-error{background:#fef2f2;color:#991b1b;border-color:#fecaca}
.empty{padding:42px 16px;text-align:center;color:var(--muted);font-weight:700}
@media (max-width:960px){.filters{grid-template-columns:1fr 1fr}.page-wrap{padding:14px}.hero-card{padding:20px;border-radius:22px}}
@media (max-width:640px){.filters{grid-template-columns:1fr}.hero-title h1{font-size:24px}.stats-grid{grid-template-columns:1fr 1fr}.brand-cell{min-width:210px}}
@media (max-width:460px){.stats-grid{grid-template-columns:1fr}}
</style>

<div class="page-wrap">
    <div class="hero-card">
        <div class="hero-title">
            <h1>إدارة الشركات / البراندات</h1>
            <p>موديول مرتب ومتناسق مع لوحة التحكم لإدارة البراندات وربطها بالمنتجات الموجودة حالياً عن طريق <strong>brand_part</strong>.</p>
        </div>
        <div class="hero-actions">
            <a href="create.php" class="hero-btn">+ إضافة براند</a>
            <a href="index.php" class="ghost-btn">تحديث الصفحة</a>
        </div>
    </div>

    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'added'): ?>
        <div class="alert alert-success">تمت إضافة البراند بنجاح.</div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'updated'): ?>
        <div class="alert alert-success">تم تحديث البراند بنجاح.</div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'deleted'): ?>
        <div class="alert alert-success">تم حذف البراند بنجاح.</div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'blocked'): ?>
        <div class="alert alert-error">لا يمكن حذف البراند لأن هناك منتجات مرتبطة به حالياً.</div>
    <?php endif; ?>
    <?php if (isset($_GET['msg']) && $_GET['msg'] === 'notfound'): ?>
        <div class="alert alert-error">البراند المطلوب غير موجود.</div>
    <?php endif; ?>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-label">إجمالي البراندات</div>
            <div class="stat-value"><?= $totalBrands ?></div>
            <div class="stat-note">كل الشركات المسجلة داخل النظام</div>
        </div>
        <div class="stat-card">
            <div class="stat-label">البراندات المفعلة</div>
            <div class="stat-value"><?= $activeBrands ?></div>
            <div class="stat-note">الظاهرة والمهيأة للاستخدام</div>
        </div>
        <div class="stat-card">
            <div class="stat-label">البراندات غير المفعلة</div>
            <div class="stat-value"><?= $inactiveBrands ?></div>
            <div class="stat-note">موجودة بالنظام لكن غير فعالة</div>
        </div>
        <div class="stat-card">
            <div class="stat-label">المنتجات المرتبطة</div>
            <div class="stat-value"><?= $totalLinkedProducts ?></div>
            <div class="stat-note">محسوبة من products.brand_part</div>
        </div>
    </div>

    <div class="panel">
        <div class="panel-head">
            <div>
                <h2>قائمة البراندات</h2>
                <p>بحث سريع، فلترة حسب الحالة، وتعديل أو حذف مباشر.</p>
            </div>
        </div>

        <form method="get" class="filters">
            <input class="input" type="text" name="keyword" value="<?= htmlspecialchars($keyword) ?>" placeholder="ابحث باسم البراند أو الـ slug">
            <select class="select" name="status">
                <option value="">كل الحالات</option>
                <option value="1" <?= $status === '1' ? 'selected' : '' ?>>مفعل</option>
                <option value="0" <?= $status === '0' ? 'selected' : '' ?>>غير مفعل</option>
            </select>
            <button type="submit" class="filter-btn">بحث / فلترة</button>
            <a href="index.php" class="hero-btn filter-reset">إعادة ضبط</a>
        </form>

        <div class="table-wrap">
            <table class="table">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>البراند</th>
                        <th>Slug</th>
                        <th>الترتيب</th>
                        <th>الحالة</th>
                        <th>عدد المنتجات</th>
                        <th>تاريخ الإنشاء</th>
                        <th>التحكم</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if ($result && $result->num_rows > 0): ?>
                        <?php while ($row = $result->fetch_assoc()): ?>
                            <tr>
                                <td><?= (int)$row['id'] ?></td>
                                <td>
                                    <div class="brand-cell">
                                        <?php if (!empty($row['image'])): ?>
                                            <img src="../uploads/<?= htmlspecialchars($row['image']) ?>" alt="<?= htmlspecialchars($row['name']) ?>" class="brand-thumb">
                                        <?php else: ?>
                                            <div class="brand-thumb placeholder"><?= htmlspecialchars(mb_substr($row['name'], 0, 1, 'UTF-8')) ?></div>
                                        <?php endif; ?>
                                        <div>
                                            <div class="brand-name"><?= htmlspecialchars($row['name']) ?></div>
                                            <div class="brand-desc"><?= htmlspecialchars((string)$row['description']) ?></div>
                                        </div>
                                    </div>
                                </td>
                                <td><span class="slug-chip"><?= htmlspecialchars((string)$row['slug']) ?></span></td>
                                <td><?= (int)$row['sort_order'] ?></td>
                                <td>
                                    <?php if ((int)$row['status'] === 1): ?>
                                        <span class="status-badge status-on">مفعل</span>
                                    <?php else: ?>
                                        <span class="status-badge status-off">غير مفعل</span>
                                    <?php endif; ?>
                                </td>
                                <td><span class="count-chip"><?= (int)$row['products_count'] ?> منتج</span></td>
                                <td><?= !empty($row['created_at']) ? htmlspecialchars(date('Y-m-d', strtotime($row['created_at']))) : '-' ?></td>
                                <td>
                                    <div class="action-group">
                                        <a class="btn-sm btn-edit" href="edit.php?id=<?= (int)$row['id'] ?>">تعديل</a>
                                        <?= admin_post_action_form('delete.php', 'حذف', 'btn-sm btn-delete', 'brand_delete', ['id' => (int)$row['id']], 'هل أنت متأكد من حذف هذا البراند؟'); ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" class="empty">لا توجد براندات حالياً.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>
