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

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

$q          = trim((string)($_GET['q'] ?? ''));
$categoryId = (int)($_GET['category_id'] ?? 0);
$status     = isset($_GET['status']) && $_GET['status'] !== '' ? (int)$_GET['status'] : '';
$brandPart  = trim((string)($_GET['brand_part'] ?? ''));
$page       = max(1, (int)($_GET['page'] ?? 1));
$perPage    = 20;
$offset     = ($page - 1) * $perPage;

$successMessage = $_SESSION['success_message'] ?? '';
$errorMessages  = $_SESSION['product_form_errors'] ?? [];
unset($_SESSION['success_message'], $_SESSION['product_form_errors']);

$categories = [];
$catRes = $conn->query("SELECT id, name FROM categories WHERE status = 1 ORDER BY sort_order ASC, name ASC");
if ($catRes) {
    while ($row = $catRes->fetch_assoc()) {
        $categories[] = $row;
    }
}

$brands = [];
$brandRes = $conn->query("SELECT id, name FROM brands WHERE status = 1 ORDER BY sort_order ASC, name ASC");
if ($brandRes) {
    while ($row = $brandRes->fetch_assoc()) {
        $brands[] = $row;
    }
}

$where = [];
$params = [];
$types = '';

if ($q !== '') {
    $where[] = "(p.name LIKE ? OR p.brand_part LIKE ? OR p.product_part LIKE ? OR p.sku LIKE ? OR c.name LIKE ?)";
    $like = '%' . $q . '%';
    for ($i = 0; $i < 5; $i++) {
        $params[] = $like;
        $types .= 's';
    }
}

if ($categoryId > 0) {
    $where[] = "p.category_id = ?";
    $params[] = $categoryId;
    $types .= 'i';
}

if ($status !== '') {
    $where[] = "p.status = ?";
    $params[] = $status;
    $types .= 'i';
}

if ($brandPart !== '') {
    $where[] = "p.brand_part = ?";
    $params[] = $brandPart;
    $types .= 's';
}

$whereSql = !empty($where) ? ('WHERE ' . implode(' AND ', $where)) : '';

$countSql = "
    SELECT COUNT(*) AS total
    FROM products p
    LEFT JOIN categories c ON c.id = p.category_id
    $whereSql
";

$totalRows = 0;
$countStmt = $conn->prepare($countSql);
if (!empty($params)) {
    $countStmt->bind_param($types, ...$params);
}
$countStmt->execute();
$countRes = $countStmt->get_result();
if ($countRes) {
    $totalRows = (int)($countRes->fetch_assoc()['total'] ?? 0);
}
$countStmt->close();

$totalPages = max(1, (int)ceil($totalRows / $perPage));

$listSql = "
    SELECT
        p.id,
        p.category_id,
        p.brand_part,
        p.product_part,
        p.name,
        p.slug,
        p.sku,
        p.main_image,
        p.price,
        p.stock_qty,
        p.low_stock_alert,
        p.has_variants,
        p.variants_same_price,
        p.status,
        p.sort_order,
        p.created_at,
        c.name AS category_name,
        (
            SELECT COUNT(*)
            FROM product_variants pv
            WHERE pv.product_id = p.id
        ) AS variants_count
    FROM products p
    LEFT JOIN categories c ON c.id = p.category_id
    $whereSql
    ORDER BY p.sort_order ASC, p.id DESC
    LIMIT ? OFFSET ?
";

$listStmt = $conn->prepare($listSql);
$runParams = $params;
$runTypes  = $types . 'ii';
$runParams[] = $perPage;
$runParams[] = $offset;

$listStmt->bind_param($runTypes, ...$runParams);
$listStmt->execute();
$listRes = $listStmt->get_result();

$items = [];
if ($listRes) {
    while ($row = $listRes->fetch_assoc()) {
        $items[] = $row;
    }
}
$listStmt->close();

function build_query($overrides = []) {
    $query = $_GET;
    foreach ($overrides as $k => $v) {
        if ($v === null) {
            unset($query[$k]);
        } else {
            $query[$k] = $v;
        }
    }
    return http_build_query($query);
}
?>

<style>
.products-page{
    padding:24px;
    direction:rtl;
}
.products-wrap{
    max-width:1450px;
    margin:0 auto;
}
.page-topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:16px;
    flex-wrap:wrap;
    margin-bottom:22px;
}
.page-title h1{
    margin:0 0 8px;
    font-size:30px;
    font-weight:800;
    color:#17324d;
}
.page-title p{
    margin:0;
    color:#71839a;
    font-size:14px;
}
.top-actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}
.btn-modern{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    text-decoration:none;
    border:none;
    border-radius:14px;
    padding:12px 18px;
    font-size:14px;
    font-weight:800;
    cursor:pointer;
}
.btn-modern.primary{
    background:linear-gradient(135deg,#2f80ed,#56ccf2);
    color:#fff;
}
.btn-modern.light{
    background:#fff;
    color:#24415c;
    border:1px solid #d9e6f2;
}
.alert-success{
    background:#ecfdf3;
    border:1px solid #b7ebc6;
    color:#166534;
    border-radius:18px;
    padding:14px 16px;
    margin-bottom:18px;
    font-weight:700;
}
.alert-danger{
    background:#fff1f1;
    border:1px solid #ffd5d5;
    color:#b42318;
    border-radius:18px;
    padding:14px 16px;
    margin-bottom:18px;
    font-weight:700;
}
.alert-danger div + div{
    margin-top:6px;
}
.card-box{
    background:#fff;
    border:1px solid #ebf1f6;
    border-radius:24px;
    overflow:hidden;
    box-shadow:0 12px 35px rgba(16,24,40,.05);
}
.card-body{
    padding:22px;
}
.filters-grid{
    display:grid;
    grid-template-columns:2fr 1fr 1fr 1fr auto auto;
    gap:12px;
    align-items:end;
}
.field{
    display:flex;
    flex-direction:column;
    gap:8px;
}
.field label{
    font-size:13px;
    font-weight:800;
    color:#26425c;
}
.field input,
.field select{
    width:100%;
    border:1px solid #d8e4ef;
    background:#f9fcff;
    border-radius:16px;
    padding:14px 15px;
    font-size:14px;
    color:#17324d;
    outline:none;
    box-sizing:border-box;
}
.results-head{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:14px;
    flex-wrap:wrap;
    margin:18px 0;
}
.results-head .count{
    font-weight:800;
    color:#17324d;
}
.table-wrap{
    overflow:auto;
    background:#fff;
    border:1px solid #ebf1f6;
    border-radius:24px;
    box-shadow:0 12px 35px rgba(16,24,40,.05);
}
.products-table{
    width:100%;
    border-collapse:collapse;
    min-width:1200px;
}
.products-table th,
.products-table td{
    padding:14px 12px;
    border-bottom:1px solid #edf2f7;
    text-align:right;
    vertical-align:middle;
}
.products-table th{
    background:#f8fbfe;
    color:#35506a;
    font-size:13px;
    font-weight:900;
    white-space:nowrap;
}
.products-table td{
    color:#17324d;
    font-size:14px;
}
.thumb{
    width:64px;
    height:64px;
    border-radius:16px;
    border:1px solid #deebf5;
    overflow:hidden;
    background:#f4f8fb;
    display:flex;
    align-items:center;
    justify-content:center;
}
.thumb img{
    width:100%;
    height:100%;
    object-fit:cover;
}
.thumb span{
    font-size:11px;
    color:#8ca0b4;
    font-weight:800;
}
.name-box{
    display:grid;
    gap:6px;
}
.name-box strong{
    font-size:14px;
    color:#17324d;
}
.name-box small{
    color:#74879c;
    font-size:12px;
}
.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:6px 10px;
    border-radius:999px;
    font-size:12px;
    font-weight:800;
    white-space:nowrap;
}
.badge.blue{ background:#eaf4ff; color:#0f5ca8; }
.badge.green{ background:#ecfdf3; color:#166534; }
.badge.red{ background:#fff1f1; color:#b42318; }
.badge.gray{ background:#f3f6f9; color:#5f7186; }
.actions{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
}
.btn-sm{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:9px 12px;
    border-radius:12px;
    text-decoration:none;
    font-size:12px;
    font-weight:800;
    border:1px solid #dbe7f1;
    background:#fff;
    color:#24415c;
}
.btn-sm.danger{
    color:#b42318;
    background:#fff1f1;
    border-color:#ffd5d5;
}
.low-stock{
    color:#b42318;
    font-weight:900;
}
.empty-state{
    text-align:center;
    color:#7f93a8;
    padding:40px 20px;
}
.pagination{
    display:flex;
    justify-content:center;
    gap:8px;
    flex-wrap:wrap;
    margin-top:20px;
}
.pagination a,
.pagination span{
    min-width:42px;
    height:42px;
    padding:0 12px;
    border-radius:12px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    text-decoration:none;
    font-size:13px;
    font-weight:800;
    border:1px solid #dbe7f1;
    background:#fff;
    color:#24415c;
}
.pagination .active{
    background:linear-gradient(135deg,#2f80ed,#56ccf2);
    color:#fff;
    border-color:transparent;
}
@media (max-width: 1100px){
    .filters-grid{
        grid-template-columns:1fr 1fr;
    }
}
@media (max-width: 768px){
    .products-page{ padding:14px; }
    .filters-grid{
        grid-template-columns:1fr;
    }
}
</style>

<div class="products-page">
    <div class="products-wrap">

        <div class="page-topbar">
            <div class="page-title">
                <h1>قائمة المنتجات</h1>
                <p>بحث، فلترة، وإدارة سريعة لكل المنتجات.</p>
            </div>

            <div class="top-actions">
                <a href="index.php" class="btn-modern light">العودة للمنتجات</a>
                <a href="create.php" class="btn-modern primary">إضافة منتج</a>
            </div>
        </div>

        <?php if ($successMessage): ?>
            <div class="alert-success"><?= e($successMessage) ?></div>
        <?php endif; ?>

        <?php if (!empty($errorMessages)): ?>
            <div class="alert-danger">
                <?php foreach ($errorMessages as $msg): ?>
                    <div>• <?= e($msg) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="card-box">
            <div class="card-body">
                <form method="get">
                    <div class="filters-grid">
                        <div class="field">
                            <label>بحث</label>
                            <input type="text" name="q" value="<?= e($q) ?>" placeholder="اسم المنتج أو البراند أو SKU">
                        </div>

                        <div class="field">
                            <label>التصنيف</label>
                            <select name="category_id">
                                <option value="">الكل</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?= (int)$cat['id'] ?>" <?= $categoryId === (int)$cat['id'] ? 'selected' : '' ?>>
                                        <?= e($cat['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="field">
                            <label>الحالة</label>
                            <select name="status">
                                <option value="">الكل</option>
                                <option value="1" <?= ($status !== '' && (int)$status === 1) ? 'selected' : '' ?>>مفعل</option>
                                <option value="0" <?= ($status !== '' && (int)$status === 0) ? 'selected' : '' ?>>غير مفعل</option>
                            </select>
                        </div>

                        <div class="field">
                            <label>البراند</label>
                            <select name="brand_part">
                                <option value="">الكل</option>
                                <?php foreach ($brands as $brand): ?>
                                    <option value="<?= e($brand['name']) ?>" <?= ($brandPart === $brand['name']) ? 'selected' : '' ?>>
                                        <?= e($brand['name']) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <button type="submit" class="btn-modern primary">فلترة</button>
                        <a href="list.php" class="btn-modern light">إعادة ضبط</a>
                    </div>
                </form>
            </div>
        </div>

        <div class="results-head">
            <div class="count">عدد النتائج: <?= number_format($totalRows) ?></div>
        </div>

        <div class="table-wrap">
            <?php if (!empty($items)): ?>
                <table class="products-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>الصورة</th>
                            <th>المنتج</th>
                            <th>التصنيف</th>
                            <th>SKU</th>
                            <th>السعر</th>
                            <th>المخزون</th>
                            <th>الفاريانتات</th>
                            <th>الحالة</th>
                            <th>الترتيب</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($items as $row): ?>
                            <?php
                                $isSimple = ((int)$row['has_variants'] === 0);
                                $isLowStock = $isSimple && ((int)$row['stock_qty'] <= (int)$row['low_stock_alert']);
                            ?>
                            <tr>
                                <td><?= (int)$row['id'] ?></td>

                                <td>
                                    <div class="thumb">
                                        <?php if (!empty($row['main_image'])): ?>
                                            <img src="../uploads/products/<?= e($row['main_image']) ?>" alt="<?= e($row['name']) ?>">
                                        <?php else: ?>
                                            <span>بدون صورة</span>
                                        <?php endif; ?>
                                    </div>
                                </td>

                                <td>
                                    <div class="name-box">
                                        <strong><?= e($row['name']) ?></strong>
                                        <small>
                                            <?= e($row['brand_part']) ?>
                                            <?php if (!empty($row['product_part'])): ?>
                                                — <?= e($row['product_part']) ?>
                                            <?php endif; ?>
                                        </small>
                                    </div>
                                </td>

                                <td><?= e($row['category_name'] ?: '—') ?></td>
                                <td><?= e($row['sku']) ?></td>

                                <td>
                                    <?php if ((int)$row['has_variants'] === 1): ?>
                                        <?php if ((int)$row['variants_same_price'] === 1): ?>
                                            <?= number_format((float)$row['price'], 0) ?> د.ع
                                        <?php else: ?>
                                            <span class="badge gray">حسب الفاريانت</span>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <?= number_format((float)$row['price'], 0) ?> د.ع
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <?php if ((int)$row['has_variants'] === 1): ?>
                                        <span class="badge gray">من الفاريانتات</span>
                                    <?php else: ?>
                                        <span class="<?= $isLowStock ? 'low-stock' : '' ?>">
                                            <?= (int)$row['stock_qty'] ?>
                                        </span>
                                        <?php if ($isLowStock): ?>
                                            <div><small style="color:#b42318;">منخفض</small></div>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <?php if ((int)$row['has_variants'] === 1): ?>
                                        <span class="badge blue"><?= (int)$row['variants_count'] ?> variant</span>
                                    <?php else: ?>
                                        <span class="badge green">بسيط</span>
                                    <?php endif; ?>
                                </td>

                                <td>
                                    <?php if ((int)$row['status'] === 1): ?>
                                        <span class="badge green">مفعل</span>
                                    <?php else: ?>
                                        <span class="badge red">غير مفعل</span>
                                    <?php endif; ?>
                                </td>

                                <td><?= (int)$row['sort_order'] ?></td>

                                <td>
                                    <div class="actions">
                                        <a class="btn-sm" href="edit.php?id=<?= (int)$row['id'] ?>">تعديل</a>

                                        <?php if ((int)$row['has_variants'] === 1): ?>
                                            <a class="btn-sm" href="variants.php?product_id=<?= (int)$row['id'] ?>">الفاريانتات</a>
                                        <?php else: ?>
                                            <a class="btn-sm" href="inventory.php?product_id=<?= (int)$row['id'] ?>">المخزون</a>
                                        <?php endif; ?>

                                        <?= admin_post_action_form(
                                            'toggle_status.php',
                                            ((int)$row['status'] === 1) ? 'إيقاف' : 'تفعيل',
                                            'btn-sm',
                                            'product_toggle',
                                            ['id' => (int)$row['id'], 'back' => $_SERVER['REQUEST_URI'] ?? '/app/admin/products/list.php'],
                                            'تأكيد تغيير حالة المنتج؟'
                                        ); ?>

                                        <?= admin_post_action_form(
                                            'delete.php',
                                            'حذف',
                                            'btn-sm danger',
                                            'product_delete',
                                            ['id' => (int)$row['id'], 'back' => $_SERVER['REQUEST_URI'] ?? '/app/admin/products/list.php'],
                                            'تأكيد حذف المنتج؟'
                                        ); ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="empty-state">ماكو نتائج مطابقة.</div>
            <?php endif; ?>
        </div>

        <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="?<?= e(build_query(['page' => $page - 1])) ?>">السابق</a>
                <?php endif; ?>

                <?php
                $start = max(1, $page - 2);
                $end   = min($totalPages, $page + 2);
                for ($i = $start; $i <= $end; $i++):
                ?>
                    <?php if ($i == $page): ?>
                        <span class="active"><?= $i ?></span>
                    <?php else: ?>
                        <a href="?<?= e(build_query(['page' => $i])) ?>"><?= $i ?></a>
                    <?php endif; ?>
                <?php endfor; ?>

                <?php if ($page < $totalPages): ?>
                    <a href="?<?= e(build_query(['page' => $page + 1])) ?>">التالي</a>
                <?php endif; ?>
            </div>
        <?php endif; ?>

    </div>
</div>

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