<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/module_hub_helpers.php';

if (function_exists('require_admin_login')) {
    require_admin_login();
}

function tp_h($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function tp_json(array $payload): void {
    if (!headers_sent()) {
        header('Content-Type: application/json; charset=utf-8');
    }
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function tp_table_exists(mysqli $conn, string $table): bool {
    $table = $conn->real_escape_string($table);
    $sql = "SHOW TABLES LIKE '{$table}'";
    $res = $conn->query($sql);
    if (!$res) {
        return false;
    }
    $exists = $res->num_rows > 0;
    $res->close();
    return $exists;
}

function tp_column_exists(mysqli $conn, string $table, string $column): bool {
    if (!tp_table_exists($conn, $table)) {
        return false;
    }
    $table = $conn->real_escape_string($table);
    $column = $conn->real_escape_string($column);
    $sql = "SHOW COLUMNS FROM `{$table}` LIKE '{$column}'";
    $res = $conn->query($sql);
    if (!$res) {
        return false;
    }
    $exists = $res->num_rows > 0;
    $res->close();
    return $exists;
}

function tp_exec(mysqli $conn, string $sql): bool {
    return (bool)$conn->query($sql);
}

function tp_query_all(mysqli $conn, string $sql): array {
    $rows = [];
    $res = $conn->query($sql);
    if (!$res) {
        return $rows;
    }
    while ($row = $res->fetch_assoc()) {
        $rows[] = $row;
    }
    $res->close();
    return $rows;
}

function tp_select_expr(mysqli $conn, string $table, string $column, string $fallback = 'NULL'): string {
    if (tp_column_exists($conn, $table, $column)) {
        return "`{$column}`";
    }
    return "{$fallback}";
}

function tp_ensure_threshold_promotions_schema(mysqli $conn): void {
    if (!tp_table_exists($conn, 'threshold_promotions')) {
        tp_exec(
            $conn,
            "CREATE TABLE `threshold_promotions` (
                `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
                `title` VARCHAR(255) NOT NULL,
                `promo_type` VARCHAR(50) NOT NULL DEFAULT 'special_price_product',
                `product_id` INT UNSIGNED NOT NULL DEFAULT 0,
                `variant_id` INT UNSIGNED NOT NULL DEFAULT 0,
                `min_subtotal` DECIMAL(12,2) NOT NULL DEFAULT 0,
                `special_price` DECIMAL(12,2) NOT NULL DEFAULT 0,
                `province_id` INT UNSIGNED NOT NULL DEFAULT 0,
                `status` TINYINT(1) NOT NULL DEFAULT 1,
                `priority` INT NOT NULL DEFAULT 0,
                `notes` TEXT NULL,
                `created_at` DATETIME NULL,
                `updated_at` DATETIME NULL,
                PRIMARY KEY (`id`),
                KEY `idx_tp_status` (`status`),
                KEY `idx_tp_product` (`product_id`),
                KEY `idx_tp_variant` (`variant_id`),
                KEY `idx_tp_province` (`province_id`),
                KEY `idx_tp_type` (`promo_type`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );
    }

    $alterMap = [
        'title' => "ADD COLUMN `title` VARCHAR(255) NOT NULL DEFAULT '' AFTER `id`",
        'promo_type' => "ADD COLUMN `promo_type` VARCHAR(50) NOT NULL DEFAULT 'special_price_product' AFTER `title`",
        'product_id' => "ADD COLUMN `product_id` INT UNSIGNED NOT NULL DEFAULT 0 AFTER `promo_type`",
        'variant_id' => "ADD COLUMN `variant_id` INT UNSIGNED NOT NULL DEFAULT 0 AFTER `product_id`",
        'min_subtotal' => "ADD COLUMN `min_subtotal` DECIMAL(12,2) NOT NULL DEFAULT 0 AFTER `variant_id`",
        'special_price' => "ADD COLUMN `special_price` DECIMAL(12,2) NOT NULL DEFAULT 0 AFTER `min_subtotal`",
        'province_id' => "ADD COLUMN `province_id` INT UNSIGNED NOT NULL DEFAULT 0 AFTER `special_price`",
        'status' => "ADD COLUMN `status` TINYINT(1) NOT NULL DEFAULT 1 AFTER `province_id`",
        'priority' => "ADD COLUMN `priority` INT NOT NULL DEFAULT 0 AFTER `status`",
        'audience_mode' => "ADD COLUMN `audience_mode` VARCHAR(20) NOT NULL DEFAULT 'all' AFTER `priority`",
        'notes' => "ADD COLUMN `notes` TEXT NULL AFTER `audience_mode`",
        'created_at' => "ADD COLUMN `created_at` DATETIME NULL AFTER `notes`",
        'updated_at' => "ADD COLUMN `updated_at` DATETIME NULL AFTER `created_at`",
    ];

    foreach ($alterMap as $column => $sql) {
        if (!tp_column_exists($conn, 'threshold_promotions', $column)) {
            tp_exec($conn, "ALTER TABLE `threshold_promotions` {$sql}");
        }
    }

    if (!tp_table_exists($conn, 'threshold_promotion_tiers')) {
        tp_exec(
            $conn,
            "CREATE TABLE `threshold_promotion_tiers` (
                `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
                `promotion_id` INT UNSIGNED NOT NULL,
                `tier_id` INT UNSIGNED NOT NULL,
                PRIMARY KEY (`id`),
                UNIQUE KEY `uniq_threshold_tier` (`promotion_id`, `tier_id`),
                KEY `idx_threshold_tier_promotion` (`promotion_id`),
                KEY `idx_threshold_tier_tier` (`tier_id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
        );
    }
}

if (!function_exists('hub_status_badge')) {
    function hub_status_badge(string $text, string $type = 'info'): string {
        $map = [
            'success' => 'tp-badge tp-badge-success',
            'warn' => 'tp-badge tp-badge-warn',
            'danger' => 'tp-badge tp-badge-danger',
            'info' => 'tp-badge tp-badge-info',
        ];
        $class = $map[$type] ?? $map['info'];
        return '<span class="' . $class . '">' . tp_h($text) . '</span>';
    }
}

tp_ensure_threshold_promotions_schema($conn);

$productNameExpr = tp_column_exists($conn, 'products', 'name') ? '`name`' : "CONCAT('منتج #', id)";
$productPriceExpr = tp_select_expr($conn, 'products', 'price', '0');
$productStatusExpr = tp_select_expr($conn, 'products', 'status', '1');
$productHasVariantsExpr = tp_select_expr($conn, 'products', 'has_variants', '0');
$productVariantsSamePriceExpr = tp_select_expr($conn, 'products', 'variants_same_price', '0');

$products = [];
if (tp_table_exists($conn, 'products')) {
    $sql = "SELECT `id`, {$productNameExpr} AS `name`, {$productPriceExpr} AS `price`, {$productStatusExpr} AS `status`, {$productHasVariantsExpr} AS `has_variants`, {$productVariantsSamePriceExpr} AS `variants_same_price` FROM `products`";
    if (tp_column_exists($conn, 'products', 'status')) {
        $sql .= ' WHERE `status` = 1';
    }
    $sql .= tp_column_exists($conn, 'products', 'name') ? ' ORDER BY `name` ASC' : ' ORDER BY `id` DESC';
    $products = tp_query_all($conn, $sql);
}

$variantNameExpr = tp_column_exists($conn, 'product_variants', 'variant_name') ? '`variant_name`' : "CONCAT('فاريانت #', id)";
$variantPriceExpr = tp_select_expr($conn, 'product_variants', 'price', '0');
$variantStockExpr = tp_select_expr($conn, 'product_variants', 'stock_qty', '0');
$variantStatusExpr = tp_select_expr($conn, 'product_variants', 'status', '1');
$variants = [];
if (tp_table_exists($conn, 'product_variants')) {
    $sql = "SELECT `id`, `product_id`, {$variantNameExpr} AS `variant_name`, {$variantPriceExpr} AS `price`, {$variantStockExpr} AS `stock_qty`, {$variantStatusExpr} AS `status` FROM `product_variants`";
    if (tp_column_exists($conn, 'product_variants', 'status')) {
        $sql .= ' WHERE `status` = 1';
    }
    $orderBy = ['`product_id` ASC'];
    if (tp_column_exists($conn, 'product_variants', 'sort_order')) {
        $orderBy[] = '`sort_order` ASC';
    }
    $orderBy[] = '`id` ASC';
    $sql .= ' ORDER BY ' . implode(', ', $orderBy);
    $variants = tp_query_all($conn, $sql);
}

$provinceNameExpr = tp_column_exists($conn, 'provinces', 'name') ? '`name`' : "CONCAT('محافظة #', id)";
$provinceStatusExpr = tp_select_expr($conn, 'provinces', 'status', '1');
$provinces = [];
if (tp_table_exists($conn, 'provinces')) {
    $sql = "SELECT `id`, {$provinceNameExpr} AS `name`, {$provinceStatusExpr} AS `status` FROM `provinces`";
    if (tp_column_exists($conn, 'provinces', 'status')) {
        $sql .= ' WHERE `status` = 1';
    }
    $sql .= tp_column_exists($conn, 'provinces', 'name') ? ' ORDER BY `name` ASC' : ' ORDER BY `id` ASC';
    $provinces = tp_query_all($conn, $sql);
}

$productMap = [];
foreach ($products as $product) {
    $productMap[(int)$product['id']] = $product;
}

$variantMap = [];
$variantsByProduct = [];
foreach ($variants as $variant) {
    $variantId = (int)($variant['id'] ?? 0);
    $productId = (int)($variant['product_id'] ?? 0);
    $variantMap[$variantId] = $variant;
    if (!isset($variantsByProduct[$productId])) {
        $variantsByProduct[$productId] = [];
    }
    $variantsByProduct[$productId][] = $variant;
}

$provinceMap = [];
foreach ($provinces as $province) {
    $provinceMap[(int)$province['id']] = $province;
}

$tiers = [];
if (tp_table_exists($conn, 'customer_tiers')) {
    $tiers = tp_query_all($conn, 'SELECT id, title, slug, color_hex FROM customer_tiers WHERE is_active = 1 ORDER BY sort_order ASC, id ASC');
}

$promotionTierMap = [];
if (tp_table_exists($conn, 'threshold_promotion_tiers')) {
    $tierRows = tp_query_all($conn, 'SELECT promotion_id, tier_id FROM threshold_promotion_tiers ORDER BY promotion_id ASC, tier_id ASC');
    foreach ($tierRows as $linkRow) {
        $promotionId = (int)($linkRow['promotion_id'] ?? 0);
        $tierId = (int)($linkRow['tier_id'] ?? 0);
        if ($promotionId > 0 && $tierId > 0) {
            $promotionTierMap[$promotionId][] = $tierId;
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = (string)($_POST['action'] ?? '');

    if ($action === 'save') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        $title = trim((string)($_POST['title'] ?? ''));
        $promoType = (string)($_POST['promo_type'] ?? 'special_price_product');
        $productId = max(0, (int)($_POST['product_id'] ?? 0));
        $variantId = max(0, (int)($_POST['variant_id'] ?? 0));
        $minSubtotal = max(0, (float)($_POST['min_subtotal'] ?? 0));
        $specialPrice = max(0, (float)($_POST['special_price'] ?? 0));
        $provinceId = max(0, (int)($_POST['province_id'] ?? 0));
        $status = ((int)($_POST['status'] ?? 1) === 1) ? 1 : 0;
        $priority = (int)($_POST['priority'] ?? 0);
        $audienceMode = in_array((string)($_POST['audience_mode'] ?? 'all'), ['all', 'tiers'], true) ? (string)$_POST['audience_mode'] : 'all';
        $audienceTierIds = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['audience_tier_ids'] ?? [])))));
        $notes = trim((string)($_POST['notes'] ?? ''));

        if ($title === '') {
            tp_json(['ok' => false, 'msg' => 'عنوان القاعدة مطلوب.']);
        }

        if (!in_array($promoType, ['special_price_product', 'free_delivery'], true)) {
            tp_json(['ok' => false, 'msg' => 'نوع القاعدة غير صالح.']);
        }

        if ($promoType === 'special_price_product') {
            if ($productId <= 0 || !isset($productMap[$productId])) {
                tp_json(['ok' => false, 'msg' => 'اختيار المنتج مطلوب.']);
            }

            $originalPrice = (float)($productMap[$productId]['price'] ?? 0);
            if ($variantId > 0) {
                if (!isset($variantMap[$variantId])) {
                    tp_json(['ok' => false, 'msg' => 'الفاريانت المختار غير موجود.']);
                }
                if ((int)($variantMap[$variantId]['product_id'] ?? 0) !== $productId) {
                    tp_json(['ok' => false, 'msg' => 'الفاريانت المختار لا يتبع المنتج المحدد.']);
                }
                $originalPrice = (float)($variantMap[$variantId]['price'] ?? $originalPrice);
            }

            if ($specialPrice <= 0) {
                tp_json(['ok' => false, 'msg' => 'السعر الخاص مطلوب ويجب أن يكون أكبر من صفر.']);
            }

            if ($originalPrice > 0 && $specialPrice >= $originalPrice) {
                tp_json(['ok' => false, 'msg' => 'السعر الخاص لازم يكون أقل من السعر الأصلي.']);
            }
        } else {
            $productId = 0;
            $variantId = 0;
            $specialPrice = 0;
        }

        if ($provinceId > 0 && !isset($provinceMap[$provinceId])) {
            tp_json(['ok' => false, 'msg' => 'المحافظة المختارة غير موجودة.']);
        }

        if ($audienceMode === 'tiers' && !$audienceTierIds) {
            tp_json(['ok' => false, 'msg' => 'اختر مستوى واحدًا على الأقل لهذا العرض.']);
        }

        if ($id > 0) {
            $stmt = $conn->prepare(
                'UPDATE `threshold_promotions` SET `title`=?, `promo_type`=?, `product_id`=?, `variant_id`=?, `min_subtotal`=?, `special_price`=?, `province_id`=?, `status`=?, `priority`=?, `audience_mode`=?, `notes`=?, `updated_at`=NOW() WHERE `id`=? LIMIT 1'
            );
            if (!$stmt) {
                tp_json(['ok' => false, 'msg' => 'تعذر تجهيز التعديل: ' . $conn->error]);
            }
            $stmt->bind_param('ssiiddiiissi', $title, $promoType, $productId, $variantId, $minSubtotal, $specialPrice, $provinceId, $status, $priority, $audienceMode, $notes, $id);
        } else {
            $stmt = $conn->prepare(
                'INSERT INTO `threshold_promotions` (`title`, `promo_type`, `product_id`, `variant_id`, `min_subtotal`, `special_price`, `province_id`, `status`, `priority`, `audience_mode`, `notes`, `created_at`, `updated_at`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())'
            );
            if (!$stmt) {
                tp_json(['ok' => false, 'msg' => 'تعذر تجهيز الإضافة: ' . $conn->error]);
            }
            $stmt->bind_param('ssiiddiiiss', $title, $promoType, $productId, $variantId, $minSubtotal, $specialPrice, $provinceId, $status, $priority, $audienceMode, $notes);
        }

        $ok = $stmt->execute();
        $msg = $ok ? 'تم حفظ قاعدة عرض الحد الأدنى بنجاح.' : ('تعذر الحفظ: ' . $stmt->error);
        $savedId = $id;
        if ($ok && $savedId <= 0) {
            $savedId = (int)$conn->insert_id;
        }
        $stmt->close();
        if ($ok && tp_table_exists($conn, 'threshold_promotion_tiers') && $savedId > 0) {
            $deleteStmt = $conn->prepare('DELETE FROM `threshold_promotion_tiers` WHERE `promotion_id` = ?');
            if ($deleteStmt) {
                $deleteStmt->bind_param('i', $savedId);
                $deleteStmt->execute();
                $deleteStmt->close();
            }
            if ($audienceMode === 'tiers' && $audienceTierIds) {
                $insertTierStmt = $conn->prepare('INSERT INTO `threshold_promotion_tiers` (`promotion_id`, `tier_id`) VALUES (?, ?)');
                if ($insertTierStmt) {
                    foreach ($audienceTierIds as $tierId) {
                        $insertTierStmt->bind_param('ii', $savedId, $tierId);
                        $insertTierStmt->execute();
                    }
                    $insertTierStmt->close();
                }
            }
        }
        tp_json(['ok' => $ok, 'msg' => $msg]);
    }

    if ($action === 'toggle') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id <= 0) {
            tp_json(['ok' => false, 'msg' => 'المعرّف غير صالح.']);
        }
        $stmt = $conn->prepare('UPDATE `threshold_promotions` SET `status` = IF(`status`=1,0,1), `updated_at`=NOW() WHERE `id`=? LIMIT 1');
        if (!$stmt) {
            tp_json(['ok' => false, 'msg' => 'تعذر تحديث الحالة: ' . $conn->error]);
        }
        $stmt->bind_param('i', $id);
        $ok = $stmt->execute();
        $stmt->close();
        tp_json(['ok' => $ok, 'msg' => $ok ? 'تم تحديث الحالة.' : 'تعذر تحديث الحالة.']);
    }

    if ($action === 'delete') {
        $id = max(0, (int)($_POST['id'] ?? 0));
        if ($id <= 0) {
            tp_json(['ok' => false, 'msg' => 'المعرّف غير صالح.']);
        }
        if (tp_table_exists($conn, 'threshold_promotion_tiers')) {
            $cleanupStmt = $conn->prepare('DELETE FROM `threshold_promotion_tiers` WHERE `promotion_id` = ?');
            if ($cleanupStmt) {
                $cleanupStmt->bind_param('i', $id);
                $cleanupStmt->execute();
                $cleanupStmt->close();
            }
        }
        $stmt = $conn->prepare('DELETE FROM `threshold_promotions` WHERE `id`=? LIMIT 1');
        if (!$stmt) {
            tp_json(['ok' => false, 'msg' => 'تعذر حذف القاعدة: ' . $conn->error]);
        }
        $stmt->bind_param('i', $id);
        $ok = $stmt->execute();
        $stmt->close();
        tp_json(['ok' => $ok, 'msg' => $ok ? 'تم حذف القاعدة.' : 'تعذر حذف القاعدة.']);
    }

    tp_json(['ok' => false, 'msg' => 'إجراء غير معروف.']);
}

$q = trim((string)($_GET['q'] ?? ''));
$typeFilter = trim((string)($_GET['promo_type'] ?? ''));
$statusFilter = trim((string)($_GET['status'] ?? ''));
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$where = [];
$types = '';
$params = [];
if ($q !== '') {
    $where[] = '(`tp`.`title` LIKE ? OR `tp`.`notes` LIKE ? OR COALESCE(`p`.`name`, "") LIKE ?)';
    $like = '%' . $q . '%';
    $types .= 'sss';
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
}
if ($typeFilter !== '' && in_array($typeFilter, ['special_price_product', 'free_delivery'], true)) {
    $where[] = '`tp`.`promo_type` = ?';
    $types .= 's';
    $params[] = $typeFilter;
}
if ($statusFilter === '1' || $statusFilter === '0') {
    $where[] = '`tp`.`status` = ?';
    $types .= 'i';
    $params[] = (int)$statusFilter;
}
$whereSql = $where ? (' WHERE ' . implode(' AND ', $where)) : '';

$countSql = 'SELECT COUNT(*) AS total FROM `threshold_promotions` `tp` LEFT JOIN `products` `p` ON `p`.`id`=`tp`.`product_id`' . $whereSql;
$countStmt = $conn->prepare($countSql);
if ($countStmt) {
    if ($types !== '') {
        $countStmt->bind_param($types, ...$params);
    }
    $countStmt->execute();
    $countRes = $countStmt->get_result();
    $totalRows = (int)(($countRes ? $countRes->fetch_assoc()['total'] : 0) ?? 0);
    if ($countRes) {
        $countRes->close();
    }
    $countStmt->close();
} else {
    $totalRows = 0;
}
$totalPages = max(1, (int)ceil($totalRows / $perPage));
if ($page > $totalPages) {
    $page = $totalPages;
    $offset = ($page - 1) * $perPage;
}

$listSql = 'SELECT `tp`.*, `p`.`name` AS `product_name`, `p`.`price` AS `product_price`, `pv`.`variant_name`, `pv`.`price` AS `variant_price`, `pr`.`name` AS `province_name`
    FROM `threshold_promotions` `tp`
    LEFT JOIN `products` `p` ON `p`.`id`=`tp`.`product_id`
    LEFT JOIN `product_variants` `pv` ON `pv`.`id`=`tp`.`variant_id`
    LEFT JOIN `provinces` `pr` ON `pr`.`id`=`tp`.`province_id`' .
    $whereSql .
    ' ORDER BY `tp`.`priority` DESC, `tp`.`min_subtotal` DESC, `tp`.`id` DESC LIMIT ? OFFSET ?';
$listStmt = $conn->prepare($listSql);
$rows = [];
if ($listStmt) {
    $bindTypes = $types . 'ii';
    $bindParams = $params;
    $bindParams[] = $perPage;
    $bindParams[] = $offset;
    $listStmt->bind_param($bindTypes, ...$bindParams);
    $listStmt->execute();
    $res = $listStmt->get_result();
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $row['audience_mode'] = (string)($row['audience_mode'] ?? 'all');
            $row['audience_tier_ids'] = array_values(array_unique(array_map('intval', $promotionTierMap[(int)($row['id'] ?? 0)] ?? [])));
            $row['audience_tier_titles'] = [];
            foreach ($tiers as $tier) {
                if (in_array((int)($tier['id'] ?? 0), $row['audience_tier_ids'], true)) {
                    $row['audience_tier_titles'][] = (string)($tier['title'] ?? '');
                }
            }
            $rows[] = $row;
        }
        $res->close();
    }
    $listStmt->close();
}

$stats = [
    'total' => $totalRows,
    'active' => 0,
    'special' => 0,
    'free_delivery' => 0,
];
$statsRes = $conn->query('SELECT `promo_type`, `status`, COUNT(*) AS total FROM `threshold_promotions` GROUP BY `promo_type`, `status`');
if ($statsRes) {
    while ($stat = $statsRes->fetch_assoc()) {
        $count = (int)($stat['total'] ?? 0);
        $promoType = (string)($stat['promo_type'] ?? '');
        $status = (int)($stat['status'] ?? 0);
        if ($status === 1) {
            $stats['active'] += $count;
        }
        if ($promoType === 'free_delivery') {
            $stats['free_delivery'] += $count;
        } else {
            $stats['special'] += $count;
        }
    }
    $statsRes->close();
}

$pageTitle = 'عروض الحد الأدنى للسلة';
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/../includes/sidebar.php';
?>
<div class="nay-dashboard-page">
    <div class="nay-dashboard-main">
        <div class="nay-dashboard-hero tp-hero">
            <div>
                <h1>عروض الحد الأدنى للسلة</h1>
                <p>إدارة احترافية لقواعد السعر الخاص والشحن المجاني مع بحث سريع للمنتجات، وإظهار السعر الأصلي، وحفظ وتعديل وحذف أكثر ثباتاً من النسخة السابقة.</p>
            </div>
            <div class="nay-actions tp-hero-actions">
                <button class="nay-btn primary" type="button" onclick="openModal()"><i class="fa-solid fa-plus"></i> إضافة قاعدة</button>
                <a class="nay-btn" href="/app/admin/settings/promotions.php"><i class="fa-solid fa-gear"></i> إعدادات العروض</a>
            </div>
        </div>

        <div class="nay-stats-grid tp-stats-grid">
            <div class="nay-card tp-stat-card">
                <div class="nay-stat-label">كل القواعد</div>
                <div class="nay-stat-value"><?= number_format($stats['total']) ?></div>
                <div class="nay-stat-sub">إجمالي قواعد العروض</div>
            </div>
            <div class="nay-card tp-stat-card">
                <div class="nay-stat-label">مفعّلة</div>
                <div class="nay-stat-value"><?= number_format($stats['active']) ?></div>
                <div class="nay-stat-sub">جاهزة للتطبيق الآن</div>
            </div>
            <div class="nay-card tp-stat-card">
                <div class="nay-stat-label">سعر خاص</div>
                <div class="nay-stat-value"><?= number_format($stats['special']) ?></div>
                <div class="nay-stat-sub">قواعد مرتبطة بمنتجات</div>
            </div>
            <div class="nay-card tp-stat-card">
                <div class="nay-stat-label">شحن مجاني</div>
                <div class="nay-stat-value"><?= number_format($stats['free_delivery']) ?></div>
                <div class="nay-stat-sub">قواعد مرتبطة بالتوصيل</div>
            </div>
        </div>

        <div class="nay-card tp-filter-card">
            <div class="nay-card-header-inline">
                <h3>البحث والتصفية</h3>
                <span>فلتر حسب العنوان أو النوع أو الحالة</span>
            </div>
            <form method="get" class="nay-form-grid tp-filter-grid">
                <div>
                    <label class="nay-label">بحث</label>
                    <input class="nay-input" type="text" name="q" value="<?= tp_h($q) ?>" placeholder="عنوان القاعدة أو اسم المنتج أو الملاحظات">
                </div>
                <div>
                    <label class="nay-label">النوع</label>
                    <select class="nay-input" name="promo_type">
                        <option value="">الكل</option>
                        <option value="special_price_product" <?= $typeFilter === 'special_price_product' ? 'selected' : '' ?>>سعر خاص لمنتج</option>
                        <option value="free_delivery" <?= $typeFilter === 'free_delivery' ? 'selected' : '' ?>>شحن مجاني</option>
                    </select>
                </div>
                <div>
                    <label class="nay-label">الحالة</label>
                    <select class="nay-input" name="status">
                        <option value="">الكل</option>
                        <option value="1" <?= $statusFilter === '1' ? 'selected' : '' ?>>مفعلة</option>
                        <option value="0" <?= $statusFilter === '0' ? 'selected' : '' ?>>موقوفة</option>
                    </select>
                </div>
                <div class="tp-filter-actions">
                    <button class="nay-btn primary" type="submit">فلترة</button>
                    <a class="nay-btn" href="index.php">إعادة ضبط</a>
                </div>
            </form>
        </div>

        <div class="nay-card tp-table-card">
            <div class="nay-card-header-inline">
                <h3>قائمة قواعد عروض الحد الأدنى</h3>
                <span><?= number_format($totalRows) ?> نتيجة</span>
            </div>

            <?php if (!$rows): ?>
                <div class="nay-empty">ماكو قواعد مطابقة حالياً.</div>
            <?php else: ?>
                <div class="nay-table-wrap tp-table-wrap">
                    <table class="nay-table tp-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>العرض</th>
                                <th>النوع</th>
                                <th>الشرط</th>
                                <th>المنتج / الأسعار</th>
                                <th>المحافظة</th>
                                <th>الحالة</th>
                                <th>التحكم</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($rows as $row):
                            $originalPrice = (float)($row['variant_price'] ?? 0);
                            if ($originalPrice <= 0) {
                                $originalPrice = (float)($row['product_price'] ?? 0);
                            }
                        ?>
                            <tr>
                                <td><?= (int)$row['id'] ?></td>
                                <td>
                                    <strong><?= tp_h($row['title'] ?? '') ?></strong>
                                    <div class="muted tp-notes">الجمهور: <?= ($row['audience_mode'] ?? 'all') === 'tiers' ? tp_h(implode(' / ', (array)($row['audience_tier_titles'] ?? [])) ?: 'مستويات محددة') : 'الجميع' ?></div>
                                    <?php if (!empty($row['notes'])): ?>
                                        <div class="muted tp-notes"><?= nl2br(tp_h($row['notes'])) ?></div>
                                    <?php else: ?>
                                        <div class="muted tp-notes">—</div>
                                    <?php endif; ?>
                                </td>
                                <td><?= ($row['promo_type'] ?? '') === 'free_delivery' ? hub_status_badge('شحن مجاني', 'info') : hub_status_badge('سعر خاص', 'success') ?></td>
                                <td>
                                    فوق <?= number_format((float)($row['min_subtotal'] ?? 0), 0) ?> د.ع
                                    <div class="muted">أولوية: <?= (int)($row['priority'] ?? 0) ?></div>
                                </td>
                                <td>
                                    <?php if (($row['promo_type'] ?? '') === 'free_delivery'): ?>
                                        <span class="muted">—</span>
                                    <?php else: ?>
                                        <strong><?= tp_h($row['product_name'] ?? '-') ?></strong>
                                        <?php if (!empty($row['variant_name'])): ?>
                                            <div class="muted"><?= tp_h($row['variant_name']) ?></div>
                                        <?php endif; ?>
                                        <div class="muted">الأصلي: <?= number_format($originalPrice, 0) ?> د.ع</div>
                                        <div class="muted">الخاص: <?= number_format((float)($row['special_price'] ?? 0), 0) ?> د.ع</div>
                                    <?php endif; ?>
                                </td>
                                <td><?= !empty($row['province_name']) ? tp_h($row['province_name']) : 'كل المحافظات' ?></td>
                                <td><?= (int)($row['status'] ?? 0) === 1 ? hub_status_badge('مفعلة', 'success') : hub_status_badge('موقوفة', 'warn') ?></td>
                                <td>
                                    <div class="tp-actions">
                                        <button class="nay-btn" type="button" onclick='openModal(<?= json_encode($row, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>)'>تعديل</button>
                                        <button class="nay-btn" type="button" onclick="toggleRow(<?= (int)$row['id'] ?>)">حالة</button>
                                        <button class="nay-btn danger" type="button" onclick="deleteRow(<?= (int)$row['id'] ?>)">حذف</button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                    <div class="tp-pagination">
                        <?php for ($i = 1; $i <= $totalPages; $i++):
                            $query = $_GET;
                            $query['page'] = $i;
                            $link = 'index.php?' . http_build_query($query);
                        ?>
                            <a class="tp-page-link <?= $i === $page ? 'is-active' : '' ?>" href="<?= tp_h($link) ?>"><?= $i ?></a>
                        <?php endfor; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="tp-modal" id="tpModal" hidden>
    <div class="tp-modal-card">
        <div class="nay-card-header-inline" style="margin-bottom:16px;">
            <h3 id="modalTitle">إضافة قاعدة</h3>
            <span>يعرض السعر الأصلي مباشرة قبل الحفظ</span>
        </div>

        <form id="saveForm" class="nay-form-grid tp-modal-grid" onsubmit="saveRow(event)">
            <input type="hidden" name="action" value="save">
            <input type="hidden" name="id" id="f_id">
            <input type="hidden" name="product_id" id="f_product_id" value="0">

            <div>
                <label class="nay-label">عنوان القاعدة</label>
                <input class="nay-input" name="title" id="f_title" required>
            </div>
            <div>
                <label class="nay-label">نوع القاعدة</label>
                <select class="nay-input" name="promo_type" id="f_promo_type">
                    <option value="special_price_product">سعر خاص لمنتج</option>
                    <option value="free_delivery">شحن مجاني</option>
                </select>
            </div>
            <div>
                <label class="nay-label">الحد الأدنى للسلة</label>
                <input class="nay-input" type="number" step="0.01" min="0" name="min_subtotal" id="f_min_subtotal" value="0">
            </div>
            <div>
                <label class="nay-label">الأولوية</label>
                <input class="nay-input" type="number" step="1" name="priority" id="f_priority" value="0">
            </div>
            <div>
                <label class="nay-label">الجمهور</label>
                <select class="nay-input" name="audience_mode" id="f_audience_mode">
                    <option value="all">الجميع</option>
                    <option value="tiers">مستويات محددة</option>
                </select>
            </div>
            <div class="tp-audience-tiers">
                <label class="nay-label">المستويات المسموحة</label>
                <div class="chips-box tp-tier-box">
                    <?php foreach ($tiers as $tier): ?>
                        <div class="chip-option">
                            <input type="checkbox" name="audience_tier_ids[]" value="<?= (int)$tier['id'] ?>" id="tp_tier_<?= (int)$tier['id'] ?>">
                            <label for="tp_tier_<?= (int)$tier['id'] ?>"><?= tp_h($tier['title']) ?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="tp-special-only" style="grid-column:1/-1;">
                <label class="nay-label">بحث عن المنتج</label>
                <input class="nay-input" type="text" id="productSearch" placeholder="اكتب اسم المنتج للبحث السريع">
                <div id="productResults" class="tp-picker-list"></div>
                <div id="selectedProductCard" class="tp-selected-product" hidden>
                    <strong id="selectedProductName">—</strong>
                    <div class="muted" id="selectedProductPrice">—</div>
                </div>
            </div>
            <div class="tp-special-only">
                <label class="nay-label">الفاريانت (اختياري)</label>
                <select class="nay-input" name="variant_id" id="f_variant_id">
                    <option value="0">كل الفاريانتات / المنتج</option>
                </select>
            </div>
            <div class="tp-special-only">
                <label class="nay-label">السعر الخاص</label>
                <input class="nay-input" type="number" step="0.01" min="0" name="special_price" id="f_special_price" value="0">
                <div class="muted" id="priceHint">الأصلي: —</div>
            </div>

            <div>
                <label class="nay-label">المحافظة المقيدة</label>
                <select class="nay-input" name="province_id" id="f_province_id">
                    <option value="0">كل المحافظات</option>
                    <?php foreach ($provinces as $province): ?>
                        <option value="<?= (int)$province['id'] ?>"><?= tp_h($province['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="nay-label">الحالة</label>
                <select class="nay-input" name="status" id="f_status">
                    <option value="1">مفعلة</option>
                    <option value="0">موقوفة</option>
                </select>
            </div>
            <div style="grid-column:1/-1;">
                <label class="nay-label">ملاحظات</label>
                <textarea class="nay-input" name="notes" id="f_notes" rows="4"></textarea>
            </div>
            <div class="tp-modal-actions">
                <button class="nay-btn primary" type="submit">حفظ</button>
                <button class="nay-btn" type="button" onclick="closeModal()">إلغاء</button>
            </div>
        </form>
    </div>
</div>
<div class="tp-toast" id="tpToast"></div>

<style>
.tp-hero{margin-bottom:18px}
.tp-hero-actions{display:flex;gap:10px;flex-wrap:wrap}
.tp-stats-grid{margin-bottom:18px}
.tp-stat-card{min-height:132px}
.tp-filter-card,.tp-table-card{margin-bottom:18px}
.tp-filter-grid,.tp-modal-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
.tp-filter-actions{display:flex;align-items:end;gap:10px;flex-wrap:wrap}
.nay-label{display:block;margin-bottom:6px;font-size:13px;font-weight:700;color:#334155}
.nay-input{width:100%;padding:11px 12px;border:1px solid #dbe3ef;border-radius:12px;background:#fff;font:inherit;transition:border-color .18s ease, box-shadow .18s ease}
.nay-input:focus{outline:none;border-color:#94a3b8;box-shadow:0 0 0 4px rgba(148,163,184,.15)}
textarea.nay-input{resize:vertical}
.tp-table-wrap{overflow:auto}
.tp-table td{vertical-align:top}
.tp-notes{margin-top:6px;line-height:1.65}
.tp-actions{display:flex;gap:8px;flex-wrap:wrap}
.nay-btn.danger{background:#fee2e2;color:#991b1b;border-color:#fecaca}
.tp-modal{position:fixed;inset:0;background:rgba(15,23,42,.46);display:flex;align-items:center;justify-content:center;padding:18px;z-index:1600}
.tp-modal[hidden]{display:none !important}
.tp-modal-card{width:min(980px,100%);background:#fff;border-radius:22px;padding:24px;box-shadow:0 24px 60px rgba(15,23,42,.22);max-height:calc(100vh - 36px);overflow:auto}
.tp-modal-actions{grid-column:1/-1;display:flex;gap:10px;justify-content:flex-end;flex-wrap:wrap}
.tp-audience-tiers{grid-column:1/-1}
.tp-tier-box{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
.tp-toast{position:fixed;top:16px;left:16px;background:#16a34a;color:#fff;padding:12px 16px;border-radius:12px;display:none;z-index:1700;box-shadow:0 18px 40px rgba(0,0,0,.16)}
.tp-toast.error{background:#dc2626}
.tp-picker-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;margin-top:10px;max-height:240px;overflow:auto}
.tp-picker-item{border:1px solid #dbe3ef;border-radius:14px;padding:12px;cursor:pointer;background:#f8fafc;text-align:right;transition:all .18s ease}
.tp-picker-item:hover,.tp-picker-item.active{border-color:#94a3b8;background:#eef2ff}
.tp-selected-product{margin-top:10px;padding:12px;border:1px dashed #cbd5e1;border-radius:14px;background:#f8fafc}
.tp-hidden{display:none !important}
.tp-pagination{display:flex;gap:8px;justify-content:center;flex-wrap:wrap;margin-top:16px}
.tp-page-link{min-width:40px;height:40px;display:inline-flex;align-items:center;justify-content:center;border-radius:12px;border:1px solid #dbe3ef;background:#fff;color:#334155;text-decoration:none;font-weight:700}
.tp-page-link.is-active,.tp-page-link:hover{background:#0f172a;color:#fff;border-color:#0f172a}
.tp-badge{display:inline-flex;align-items:center;justify-content:center;padding:5px 10px;border-radius:999px;font-size:12px;font-weight:700;white-space:nowrap}
.tp-badge-success{background:#dcfce7;color:#166534}
.tp-badge-warn{background:#fef3c7;color:#92400e}
.tp-badge-danger{background:#fee2e2;color:#991b1b}
.tp-badge-info{background:#dbeafe;color:#1d4ed8}
@media (max-width: 900px){
    .tp-filter-grid,.tp-modal-grid,.tp-picker-list,.tp-tier-box{grid-template-columns:1fr}
    .tp-modal-card{padding:18px}
}
</style>
<script>
const products = <?= json_encode(array_map(static function($p){ return [
    'id' => (int)($p['id'] ?? 0),
    'name' => (string)($p['name'] ?? ''),
    'price' => (float)($p['price'] ?? 0),
    'has_variants' => (int)($p['has_variants'] ?? 0),
]; }, $products), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
const variants = <?= json_encode(array_map(static function($v){ return [
    'id' => (int)($v['id'] ?? 0),
    'product_id' => (int)($v['product_id'] ?? 0),
    'variant_name' => (string)($v['variant_name'] ?? ''),
    'price' => (float)($v['price'] ?? 0),
    'stock_qty' => (int)($v['stock_qty'] ?? 0),
]; }, $variants), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

const modal = document.getElementById('tpModal');
const toastEl = document.getElementById('tpToast');
const productSearch = document.getElementById('productSearch');
const productResults = document.getElementById('productResults');
const selectedProductCard = document.getElementById('selectedProductCard');
const selectedProductName = document.getElementById('selectedProductName');
const selectedProductPrice = document.getElementById('selectedProductPrice');
const priceHint = document.getElementById('priceHint');

function toast(message, isError = false) {
    toastEl.textContent = message || 'تم';
    toastEl.className = 'tp-toast' + (isError ? ' error' : '');
    toastEl.style.display = 'block';
    window.clearTimeout(window.__tpToastTimer);
    window.__tpToastTimer = window.setTimeout(() => {
        toastEl.style.display = 'none';
    }, 2600);
}

function currency(value) {
    return new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 }).format(Number(value || 0)) + ' د.ع';
}

function closeModal() {
    modal.hidden = true;
}

function syncType() {
    const isSpecial = document.getElementById('f_promo_type').value === 'special_price_product';
    document.querySelectorAll('.tp-special-only').forEach((el) => {
        el.classList.toggle('tp-hidden', !isSpecial);
    });
}

function syncAudience() {
    const isTierAudience = document.getElementById('f_audience_mode').value === 'tiers';
    document.querySelectorAll('.tp-audience-tiers').forEach((el) => {
        el.classList.toggle('tp-hidden', !isTierAudience);
    });
}

function syncVariants(selected = 0) {
    const productId = Number(document.getElementById('f_product_id').value || 0);
    const select = document.getElementById('f_variant_id');
    select.innerHTML = '<option value="0">كل الفاريانتات / المنتج</option>';
    variants.filter((variant) => variant.product_id === productId).forEach((variant) => {
        const option = document.createElement('option');
        option.value = String(variant.id);
        option.textContent = `${variant.variant_name} — ${currency(variant.price)}`;
        if (Number(selected) === Number(variant.id)) {
            option.selected = true;
        }
        select.appendChild(option);
    });
    updateOriginalPriceHint();
}

function updateOriginalPriceHint() {
    const productId = Number(document.getElementById('f_product_id').value || 0);
    const variantId = Number(document.getElementById('f_variant_id').value || 0);
    const product = products.find((item) => item.id === productId);
    let original = product ? Number(product.price || 0) : 0;

    if (variantId > 0) {
        const variant = variants.find((item) => item.id === variantId);
        if (variant) {
            original = Number(variant.price || 0);
        }
    }

    priceHint.textContent = 'الأصلي: ' + (original > 0 ? currency(original) : '—');
    if (product) {
        selectedProductCard.hidden = false;
        selectedProductName.textContent = product.name;
        selectedProductPrice.textContent = 'السعر الأصلي: ' + (original > 0 ? currency(original) : '—');
    } else {
        selectedProductCard.hidden = true;
        selectedProductName.textContent = '—';
        selectedProductPrice.textContent = '—';
    }
}

function chooseProduct(id) {
    document.getElementById('f_product_id').value = String(id);
    const product = products.find((item) => item.id === Number(id));
    productSearch.value = product ? product.name : '';
    renderProducts(productSearch.value);
    syncVariants(0);
}

function renderProducts(query = '') {
    const q = String(query || '').trim().toLowerCase();
    let rows = products;
    if (q) {
        rows = rows.filter((product) => String(product.name || '').toLowerCase().includes(q));
    }

    productResults.innerHTML = '';
    if (!rows.length) {
        productResults.innerHTML = '<div class="muted">ماكو نتائج مطابقة.</div>';
        return;
    }

    rows.slice(0, 18).forEach((product) => {
        const item = document.createElement('button');
        item.type = 'button';
        item.className = 'tp-picker-item' + (Number(document.getElementById('f_product_id').value || 0) === product.id ? ' active' : '');
        item.innerHTML = `<strong>${product.name}</strong><div class="muted">${currency(product.price || 0)}</div>`;
        item.onclick = () => chooseProduct(product.id);
        productResults.appendChild(item);
    });
}

function openModal(row = null) {
    const form = document.getElementById('saveForm');
    form.reset();
    document.getElementById('f_id').value = '';
    document.getElementById('f_product_id').value = '0';
    document.getElementById('modalTitle').textContent = row ? 'تعديل القاعدة' : 'إضافة قاعدة';
    document.querySelectorAll('input[name="audience_tier_ids[]"]').forEach((checkbox) => {
        checkbox.checked = false;
    });

    if (row) {
        Object.keys(row).forEach((key) => {
            const field = document.getElementById('f_' + key);
            if (field) {
                field.value = row[key] ?? '';
            }
        });

        document.getElementById('f_product_id').value = String(row.product_id || 0);
        const product = products.find((item) => item.id === Number(row.product_id || 0));
        productSearch.value = product ? product.name : '';
        syncVariants(row.variant_id || 0);
        (row.audience_tier_ids || []).forEach((tierId) => {
            const checkbox = document.getElementById('tp_tier_' + tierId);
            if (checkbox) {
                checkbox.checked = true;
            }
        });
    } else {
        productSearch.value = '';
        renderProducts('');
        syncVariants(0);
    }

    syncType();
    syncAudience();
    updateOriginalPriceHint();
    modal.hidden = false;
    renderProducts(productSearch.value);
}

async function postData(data) {
    const body = new URLSearchParams(data instanceof FormData ? [...data.entries()] : Object.entries(data));
    const response = await fetch('index.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
        body,
    });

    const raw = await response.text();
    try {
        return JSON.parse(raw);
    } catch (error) {
        return {
            ok: false,
            msg: raw ? ('استجابة غير متوقعة من السيرفر: ' + raw.slice(0, 220)) : 'استجابة فارغة من السيرفر.',
        };
    }
}

async function saveRow(event) {
    event.preventDefault();
    const result = await postData(new FormData(event.target));
    toast(result.msg, !result.ok);
    if (result.ok) {
        window.setTimeout(() => window.location.reload(), 650);
    }
}

async function toggleRow(id) {
    const result = await postData({ action: 'toggle', id });
    toast(result.msg, !result.ok);
    if (result.ok) {
        window.setTimeout(() => window.location.reload(), 450);
    }
}

async function deleteRow(id) {
    if (!window.confirm('تأكيد حذف القاعدة؟')) {
        return;
    }
    const result = await postData({ action: 'delete', id });
    toast(result.msg, !result.ok);
    if (result.ok) {
        window.setTimeout(() => window.location.reload(), 450);
    }
}

document.getElementById('f_promo_type').addEventListener('change', syncType);
document.getElementById('f_audience_mode').addEventListener('change', syncAudience);
document.getElementById('f_variant_id').addEventListener('change', updateOriginalPriceHint);
productSearch.addEventListener('input', () => renderProducts(productSearch.value));
modal.addEventListener('click', (event) => {
    if (event.target === modal) {
        closeModal();
    }
});
renderProducts('');
syncType();
syncAudience();
</script>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
