<?php
// Promo Codes Module Helpers
// Built for Nay Store admin structure: app/admin/promo_codes/

if (!function_exists('promo_db')) {
    function promo_db()
    {
        global $conn, $mysqli, $db;

        if (isset($conn) && $conn instanceof mysqli) {
            return $conn;
        }
        if (isset($mysqli) && $mysqli instanceof mysqli) {
            return $mysqli;
        }
        if (isset($db) && $db instanceof mysqli) {
            return $db;
        }
        if (function_exists('db')) {
            $maybe = db();
            if ($maybe instanceof mysqli) {
                return $maybe;
            }
        }

        throw new RuntimeException('Database connection not found. Check includes/config.php');
    }
}

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

if (!function_exists('promo_money')) {
    function promo_money($value)
    {
        return number_format((float)$value, 0) . ' د.ع';
    }
}

if (!function_exists('promo_datetime')) {
    function promo_datetime($value)
    {
        if (empty($value) || $value === '0000-00-00 00:00:00') {
            return '-';
        }

        $ts = strtotime($value);
        return $ts ? date('Y-m-d h:i A', $ts) : (string)$value;
    }
}

if (!function_exists('promo_datetime_local_value')) {
    function promo_datetime_local_value($value)
    {
        if (empty($value) || $value === '0000-00-00 00:00:00') {
            return '';
        }

        $ts = strtotime($value);
        return $ts ? date('Y-m-d\TH:i', $ts) : '';
    }
}

if (!function_exists('promo_datetime_to_db')) {
    function promo_datetime_to_db($value)
    {
        $value = trim((string)$value);
        if ($value === '') {
            return null;
        }

        $ts = strtotime($value);
        if (!$ts) {
            return false;
        }

        return date('Y-m-d H:i:s', $ts);
    }
}

if (!function_exists('promo_status_badge')) {
    function promo_status_badge($status)
    {
        return ((int)$status === 1)
            ? '<span style="display:inline-block;padding:4px 10px;border-radius:999px;background:#dcfce7;color:#166534;font-size:12px;">نشط</span>'
            : '<span style="display:inline-block;padding:4px 10px;border-radius:999px;background:#fee2e2;color:#991b1b;font-size:12px;">غير نشط</span>';
    }
}

if (!function_exists('promo_discount_text')) {
    function promo_discount_text($type, $value)
    {
        if ($type === 'fixed') {
            return promo_money($value);
        }

        return rtrim(rtrim(number_format((float)$value, 2), '0'), '.') . '%';
    }
}

if (!function_exists('promo_validity_badge')) {
    function promo_validity_badge($row)
    {
        $isValid = promo_is_currently_valid($row);
        return $isValid
            ? '<span style="display:inline-block;padding:4px 10px;border-radius:999px;background:#dbeafe;color:#1d4ed8;font-size:12px;">صالح الآن</span>'
            : '<span style="display:inline-block;padding:4px 10px;border-radius:999px;background:#f3f4f6;color:#374151;font-size:12px;">غير صالح الآن</span>';
    }
}

if (!function_exists('promo_fetch_all')) {
    function promo_fetch_all($stmt)
    {
        $result = $stmt->get_result();
        return $result ? ($result->fetch_all(MYSQLI_ASSOC) ?: array()) : array();
    }
}

if (!function_exists('promo_fetch_one')) {
    function promo_fetch_one($stmt)
    {
        $result = $stmt->get_result();
        if (!$result) {
            return null;
        }

        $row = $result->fetch_assoc();
        return $row ?: null;
    }
}

if (!function_exists('promo_bind_params')) {
    function promo_bind_params($stmt, $types, $params)
    {
        if ($types === '' || empty($params)) {
            return;
        }

        $refs = array();
        foreach ($params as $key => $value) {
            $refs[$key] = &$params[$key];
        }
        array_unshift($refs, $types);
        call_user_func_array(array($stmt, 'bind_param'), $refs);
    }
}


if (!function_exists('promo_has_column')) {
    function promo_has_column(string $table, string $column): bool
    {
        $db = promo_db();
        $safeTable = $db->real_escape_string($table);
        $safeColumn = $db->real_escape_string($column);
        $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeColumn}'");
        return $res instanceof mysqli_result && $res->num_rows > 0;
    }
}

if (!function_exists('promo_redirect')) {
    function promo_redirect($url)
    {
        header('Location: ' . $url);
        exit;
    }
}

if (!function_exists('promo_prepare_result')) {
    function promo_prepare_result($ok, $message, $extra = array())
    {
        return array_merge(array('ok' => (bool)$ok, 'message' => (string)$message), $extra);
    }
}

if (!function_exists('promo_default_data')) {
    function promo_default_data()
    {
        return array(
            'id' => 0,
            'title' => '',
            'code' => '',
            'discount_type' => 'percent',
            'discount_value' => '0',
            'minimum_order_amount' => '0',
            'maximum_discount_amount' => '',
            'usage_limit' => '',
            'used_count' => 0,
            'start_at' => '',
            'end_at' => '',
            'is_single_use_per_customer' => 0,
            'first_order_only' => 0,
            'status' => 1,
            'notes' => '',
            'created_at' => '',
            'updated_at' => '',
        );
    }
}

if (!function_exists('promo_fill_input')) {
    function promo_fill_input($data, $base = null)
    {
        $row = is_array($base) ? $base : promo_default_data();

        $row['title'] = trim((string)($data['title'] ?? $row['title']));
        $row['code'] = strtoupper(trim((string)($data['code'] ?? $row['code'])));
        $row['discount_type'] = (string)($data['discount_type'] ?? $row['discount_type']);
        $row['discount_value'] = trim((string)($data['discount_value'] ?? $row['discount_value']));
        $row['minimum_order_amount'] = trim((string)($data['minimum_order_amount'] ?? $row['minimum_order_amount']));
        $row['maximum_discount_amount'] = trim((string)($data['maximum_discount_amount'] ?? $row['maximum_discount_amount']));
        $row['usage_limit'] = trim((string)($data['usage_limit'] ?? $row['usage_limit']));
        $row['start_at'] = trim((string)($data['start_at'] ?? $row['start_at']));
        $row['end_at'] = trim((string)($data['end_at'] ?? $row['end_at']));
        $row['is_single_use_per_customer'] = (($data['is_single_use_per_customer'] ?? $row['is_single_use_per_customer']) == 1) ? 1 : 0;
        $row['first_order_only'] = (($data['first_order_only'] ?? $row['first_order_only'] ?? 0) == 1) ? 1 : 0;
        $row['status'] = (($data['status'] ?? $row['status']) == 1) ? 1 : 0;
        $row['notes'] = trim((string)($data['notes'] ?? $row['notes']));

        return $row;
    }
}

if (!function_exists('promo_code_exists')) {
    function promo_code_exists($code, $excludeId = 0)
    {
        $db = promo_db();
        $code = strtoupper(trim((string)$code));
        if ($code === '') {
            return false;
        }

        $sql = 'SELECT id FROM promo_codes WHERE code = ?' . ($excludeId > 0 ? ' AND id <> ?' : '') . ' LIMIT 1';
        $stmt = $db->prepare($sql);
        if ($excludeId > 0) {
            $stmt->bind_param('si', $code, $excludeId);
        } else {
            $stmt->bind_param('s', $code);
        }
        $stmt->execute();
        $row = promo_fetch_one($stmt);
        $stmt->close();

        return !empty($row);
    }
}

if (!function_exists('promo_validate_data')) {
    function promo_validate_data($data, $promoId = 0)
    {
        $title = trim((string)($data['title'] ?? ''));
        $code = strtoupper(trim((string)($data['code'] ?? '')));
        $discountType = (string)($data['discount_type'] ?? 'percent');
        $discountValue = trim((string)($data['discount_value'] ?? ''));
        $minimumOrder = trim((string)($data['minimum_order_amount'] ?? '0'));
        $maximumDiscount = trim((string)($data['maximum_discount_amount'] ?? ''));
        $usageLimit = trim((string)($data['usage_limit'] ?? ''));
        $startAt = trim((string)($data['start_at'] ?? ''));
        $endAt = trim((string)($data['end_at'] ?? ''));

        if ($title === '') {
            return promo_prepare_result(false, 'عنوان الكود مطلوب');
        }

        if ($code === '') {
            return promo_prepare_result(false, 'رمز الكود مطلوب');
        }

        if (!preg_match('/^[A-Z0-9_\-]+$/', $code)) {
            return promo_prepare_result(false, 'رمز الكود لازم يحتوي على حروف إنكليزية كبيرة أو أرقام أو - أو _ فقط');
        }

        if (promo_code_exists($code, $promoId)) {
            return promo_prepare_result(false, 'رمز الكود مستخدم مسبقاً');
        }

        $allowedTypes = array('percent', 'fixed');
        if (!in_array($discountType, $allowedTypes, true)) {
            return promo_prepare_result(false, 'نوع الخصم غير صحيح');
        }

        if ($discountValue === '' || !is_numeric($discountValue) || (float)$discountValue <= 0) {
            return promo_prepare_result(false, 'قيمة الخصم لازم تكون أكبر من صفر');
        }

        if ($discountType === 'percent' && (float)$discountValue > 100) {
            return promo_prepare_result(false, 'الخصم النسبي لا يمكن أن يتجاوز 100%');
        }

        if ($minimumOrder === '' || !is_numeric($minimumOrder) || (float)$minimumOrder < 0) {
            return promo_prepare_result(false, 'الحد الأدنى للطلب غير صحيح');
        }

        if ($maximumDiscount !== '' && (!is_numeric($maximumDiscount) || (float)$maximumDiscount < 0)) {
            return promo_prepare_result(false, 'الحد الأعلى للخصم غير صحيح');
        }

        if ($usageLimit !== '' && (!ctype_digit($usageLimit) || (int)$usageLimit < 1)) {
            return promo_prepare_result(false, 'حد الاستخدام يجب أن يكون رقم صحيح أكبر من صفر');
        }

        $dbStartAt = promo_datetime_to_db($startAt);
        if ($startAt !== '' && $dbStartAt === false) {
            return promo_prepare_result(false, 'صيغة وقت البداية غير صحيحة');
        }

        $dbEndAt = promo_datetime_to_db($endAt);
        if ($endAt !== '' && $dbEndAt === false) {
            return promo_prepare_result(false, 'صيغة وقت النهاية غير صحيحة');
        }

        if ($dbStartAt && $dbEndAt && strtotime($dbStartAt) > strtotime($dbEndAt)) {
            return promo_prepare_result(false, 'وقت النهاية لازم يكون بعد وقت البداية');
        }

        return promo_prepare_result(true, 'البيانات سليمة');
    }
}

if (!function_exists('promo_save_data')) {
    function promo_save_data($data, $promoId = 0)
    {
        $db = promo_db();
        $promoId = (int)$promoId;

        $validation = promo_validate_data($data, $promoId);
        if (!$validation['ok']) {
            return $validation;
        }

        $title = trim((string)$data['title']);
        $code = strtoupper(trim((string)$data['code']));
        $discountType = (string)$data['discount_type'];
        $discountValue = (float)$data['discount_value'];
        $minimumOrder = (float)$data['minimum_order_amount'];
        $maximumDiscount = trim((string)$data['maximum_discount_amount']);
        $usageLimit = trim((string)$data['usage_limit']);
        $startAt = promo_datetime_to_db((string)($data['start_at'] ?? ''));
        $endAt = promo_datetime_to_db((string)($data['end_at'] ?? ''));
        $singleUse = ((int)($data['is_single_use_per_customer'] ?? 0) === 1) ? 1 : 0;
        $firstOrderOnly = ((int)($data['first_order_only'] ?? 0) === 1) ? 1 : 0;
        $status = ((int)($data['status'] ?? 0) === 1) ? 1 : 0;
        $notes = trim((string)($data['notes'] ?? ''));
        $hasFirstOrderOnly = promo_has_column('promo_codes', 'first_order_only');

        if ($promoId > 0) {
            $sql = 'UPDATE promo_codes
                    SET title = ?,
                        code = ?,
                        discount_type = ?,
                        discount_value = ?,
                        minimum_order_amount = ?,
                        maximum_discount_amount = NULLIF(?, ""),
                        usage_limit = NULLIF(?, ""),
                        start_at = NULLIF(?, ""),
                        end_at = NULLIF(?, ""),
                        is_single_use_per_customer = ?,' .
                        ($hasFirstOrderOnly ? ' first_order_only = ?,' : '') . '
                        status = ?,
                        notes = ?
                    WHERE id = ? LIMIT 1';
            $stmt = $db->prepare($sql);
            if ($hasFirstOrderOnly) {
                $stmt->bind_param(
                    'sssddssssiiisi',
                    $title,
                    $code,
                    $discountType,
                    $discountValue,
                    $minimumOrder,
                    $maximumDiscount,
                    $usageLimit,
                    $startAt,
                    $endAt,
                    $singleUse,
                    $firstOrderOnly,
                    $status,
                    $notes,
                    $promoId
                );
            } else {
                $stmt->bind_param(
                    'sssddssssiisi',
                    $title,
                    $code,
                    $discountType,
                    $discountValue,
                    $minimumOrder,
                    $maximumDiscount,
                    $usageLimit,
                    $startAt,
                    $endAt,
                    $singleUse,
                    $status,
                    $notes,
                    $promoId
                );
            }
            $ok = $stmt->execute();
            $stmt->close();

            return $ok
                ? promo_prepare_result(true, 'تم تحديث كود الخصم بنجاح', array('id' => $promoId))
                : promo_prepare_result(false, 'تعذر تحديث كود الخصم');
        }

        $columns = 'title, code, discount_type, discount_value, minimum_order_amount, maximum_discount_amount, usage_limit, start_at, end_at, is_single_use_per_customer';
        $values = '?, ?, ?, ?, ?, NULLIF(?, ""), NULLIF(?, ""), NULLIF(?, ""), NULLIF(?, ""), ?';
        if ($hasFirstOrderOnly) {
            $columns .= ', first_order_only';
            $values .= ', ?';
        }
        $columns .= ', status, notes';
        $values .= ', ?, ?';

        $sql = 'INSERT INTO promo_codes (' . $columns . ') VALUES (' . $values . ')';
        $stmt = $db->prepare($sql);
        if ($hasFirstOrderOnly) {
            $stmt->bind_param(
                'sssddssssiiis',
                $title,
                $code,
                $discountType,
                $discountValue,
                $minimumOrder,
                $maximumDiscount,
                $usageLimit,
                $startAt,
                $endAt,
                $singleUse,
                $firstOrderOnly,
                $status,
                $notes
            );
        } else {
            $stmt->bind_param(
                'sssddssssiis',
                $title,
                $code,
                $discountType,
                $discountValue,
                $minimumOrder,
                $maximumDiscount,
                $usageLimit,
                $startAt,
                $endAt,
                $singleUse,
                $status,
                $notes
            );
        }
        $ok = $stmt->execute();
        $newId = $ok ? (int)$stmt->insert_id : 0;
        $stmt->close();

        return $ok
            ? promo_prepare_result(true, 'تم إنشاء كود الخصم بنجاح', array('id' => $newId))
            : promo_prepare_result(false, 'تعذر إنشاء كود الخصم');
    }
}

if (!function_exists('promo_create_code')) {
    function promo_create_code($data)
    {
        return promo_save_data($data, 0);
    }
}

if (!function_exists('promo_update_code')) {
    function promo_update_code($promoId, $data)
    {
        return promo_save_data($data, (int)$promoId);
    }
}

if (!function_exists('promo_set_status')) {
    function promo_set_status($promoId, $value)
    {
        $db = promo_db();
        $promoId = (int)$promoId;
        $value = ((int)$value === 1) ? 1 : 0;

        if ($promoId < 1) {
            return promo_prepare_result(false, 'معرف كود الخصم غير صالح');
        }

        $stmt = $db->prepare('UPDATE promo_codes SET status = ? WHERE id = ? LIMIT 1');
        $stmt->bind_param('ii', $value, $promoId);
        $ok = $stmt->execute();
        $stmt->close();

        return $ok
            ? promo_prepare_result(true, $value === 1 ? 'تم تفعيل كود الخصم' : 'تم تعطيل كود الخصم')
            : promo_prepare_result(false, 'تعذر تحديث حالة كود الخصم');
    }
}

if (!function_exists('promo_is_currently_valid')) {
    function promo_is_currently_valid($row)
    {
        if (empty($row) || (int)($row['status'] ?? 0) !== 1) {
            return false;
        }

        $now = time();
        $startAt = !empty($row['start_at']) ? strtotime($row['start_at']) : null;
        $endAt = !empty($row['end_at']) ? strtotime($row['end_at']) : null;
        $usageLimit = isset($row['usage_limit']) && $row['usage_limit'] !== null && $row['usage_limit'] !== '' ? (int)$row['usage_limit'] : null;
        $usedCount = (int)($row['used_count'] ?? 0);

        if ($startAt && $now < $startAt) {
            return false;
        }

        if ($endAt && $now > $endAt) {
            return false;
        }

        if ($usageLimit !== null && $usedCount >= $usageLimit) {
            return false;
        }

        return true;
    }
}

if (!function_exists('promo_get_stats')) {
    function promo_get_stats()
    {
        $db = promo_db();

        $stats = array(
            'total_codes' => 0,
            'active_codes' => 0,
            'inactive_codes' => 0,
            'single_use_codes' => 0,
            'first_order_codes' => 0,
            'total_used_count' => 0,
            'usage_rows' => 0,
            'currently_valid' => 0,
        );

        $hasFirstOrderOnly = promo_has_column('promo_codes', 'first_order_only');
        $sql = 'SELECT 
                    COUNT(*) AS total_codes,
                    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS active_codes,
                    SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS inactive_codes,
                    SUM(CASE WHEN is_single_use_per_customer = 1 THEN 1 ELSE 0 END) AS single_use_codes,' .
                    ($hasFirstOrderOnly ? ' SUM(CASE WHEN first_order_only = 1 THEN 1 ELSE 0 END) AS first_order_codes,' : ' 0 AS first_order_codes,') . '
                    SUM(used_count) AS total_used_count,
                    SUM(CASE
                        WHEN status = 1
                         AND (start_at IS NULL OR start_at <= NOW())
                         AND (end_at IS NULL OR end_at >= NOW())
                         AND (usage_limit IS NULL OR used_count < usage_limit)
                        THEN 1 ELSE 0 END) AS currently_valid
                FROM promo_codes';
        $row = $db->query($sql);
        if ($row) {
            $data = $row->fetch_assoc();
            if ($data) {
                $stats = array_merge($stats, array_map('intval', $data));
            }
        }

        $row = $db->query('SELECT COUNT(*) AS usage_rows FROM promo_code_usage');
        if ($row) {
            $data = $row->fetch_assoc();
            if ($data) {
                $stats['usage_rows'] = (int)$data['usage_rows'];
            }
        }

        return $stats;
    }
}

if (!function_exists('promo_get_codes')) {
    function promo_get_codes($request, $page = 1, $perPage = 20)
    {
        $db = promo_db();
        $page = max(1, (int)$page);
        $perPage = max(1, (int)$perPage);
        $offset = ($page - 1) * $perPage;

        $filters = array(
            'q' => trim((string)($request['q'] ?? '')),
            'status' => trim((string)($request['status'] ?? '')),
            'discount_type' => trim((string)($request['discount_type'] ?? '')),
            'active_now' => trim((string)($request['active_now'] ?? '')),
        );

        $where = array();
        $types = '';
        $params = array();

        if ($filters['q'] !== '') {
            $where[] = '(pc.title LIKE ? OR pc.code LIKE ? OR pc.notes LIKE ?)';
            $like = '%' . $filters['q'] . '%';
            $types .= 'sss';
            $params[] = $like;
            $params[] = $like;
            $params[] = $like;
        }

        if ($filters['status'] === '1' || $filters['status'] === '0') {
            $where[] = 'pc.status = ?';
            $types .= 'i';
            $params[] = (int)$filters['status'];
        }

        if ($filters['discount_type'] === 'percent' || $filters['discount_type'] === 'fixed') {
            $where[] = 'pc.discount_type = ?';
            $types .= 's';
            $params[] = $filters['discount_type'];
        }

        if ($filters['active_now'] === '1') {
            $where[] = 'pc.status = 1 AND (pc.start_at IS NULL OR pc.start_at <= NOW()) AND (pc.end_at IS NULL OR pc.end_at >= NOW()) AND (pc.usage_limit IS NULL OR pc.used_count < pc.usage_limit)';
        } elseif ($filters['active_now'] === '0') {
            $where[] = '(pc.status = 0 OR (pc.start_at IS NOT NULL AND pc.start_at > NOW()) OR (pc.end_at IS NOT NULL AND pc.end_at < NOW()) OR (pc.usage_limit IS NOT NULL AND pc.used_count >= pc.usage_limit))';
        }

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

        $countSql = 'SELECT COUNT(*) AS total FROM promo_codes pc' . $whereSql;
        $stmt = $db->prepare($countSql);
        promo_bind_params($stmt, $types, $params);
        $stmt->execute();
        $countRow = promo_fetch_one($stmt);
        $stmt->close();
        $total = (int)($countRow['total'] ?? 0);

        $sql = 'SELECT pc.*,
                       (SELECT COUNT(*) FROM promo_code_usage u WHERE u.promo_code_id = pc.id) AS actual_usage_rows,
                       (SELECT COUNT(DISTINCT u.customer_id) FROM promo_code_usage u WHERE u.promo_code_id = pc.id AND u.customer_id IS NOT NULL) AS distinct_customers,
                       (SELECT COUNT(*) FROM orders o WHERE o.promo_code_id = pc.id) AS orders_count
                FROM promo_codes pc'
                . $whereSql .
                ' ORDER BY pc.id DESC LIMIT ?, ?';
        $stmt = $db->prepare($sql);
        $queryTypes = $types . 'ii';
        $queryParams = $params;
        $queryParams[] = $offset;
        $queryParams[] = $perPage;
        promo_bind_params($stmt, $queryTypes, $queryParams);
        $stmt->execute();
        $rows = promo_fetch_all($stmt);
        $stmt->close();

        return array(
            'rows' => $rows,
            'page' => $page,
            'pages' => max(1, (int)ceil($total / $perPage)),
            'total' => $total,
            'per_page' => $perPage,
            'filters' => $filters,
        );
    }
}

if (!function_exists('promo_get_code')) {
    function promo_get_code($promoId)
    {
        $db = promo_db();
        $promoId = (int)$promoId;
        if ($promoId < 1) {
            return null;
        }

        $sql = 'SELECT pc.*,
                       (SELECT COUNT(*) FROM promo_code_usage u WHERE u.promo_code_id = pc.id) AS actual_usage_rows,
                       (SELECT COUNT(DISTINCT u.customer_id) FROM promo_code_usage u WHERE u.promo_code_id = pc.id AND u.customer_id IS NOT NULL) AS distinct_customers,
                       (SELECT COUNT(*) FROM orders o WHERE o.promo_code_id = pc.id) AS orders_count,
                       (SELECT COALESCE(SUM(u.discount_value), 0) FROM promo_code_usage u WHERE u.promo_code_id = pc.id) AS total_discount_given
                FROM promo_codes pc
                WHERE pc.id = ? LIMIT 1';
        $stmt = $db->prepare($sql);
        $stmt->bind_param('i', $promoId);
        $stmt->execute();
        $row = promo_fetch_one($stmt);
        $stmt->close();

        return $row ?: null;
    }
}

if (!function_exists('promo_get_recent_usage')) {
    function promo_get_recent_usage($promoId, $limit = 25)
    {
        $db = promo_db();
        $promoId = (int)$promoId;
        $limit = max(1, (int)$limit);

        $sql = 'SELECT u.*, c.full_name AS customer_name, c.phone AS customer_phone, o.order_number, o.total_amount
                FROM promo_code_usage u
                LEFT JOIN customers c ON c.id = u.customer_id
                LEFT JOIN orders o ON o.id = u.order_id
                WHERE u.promo_code_id = ?
                ORDER BY u.id DESC
                LIMIT ?';
        $stmt = $db->prepare($sql);
        $stmt->bind_param('ii', $promoId, $limit);
        $stmt->execute();
        $rows = promo_fetch_all($stmt);
        $stmt->close();

        return $rows;
    }
}

if (!function_exists('promo_get_recent_orders')) {
    function promo_get_recent_orders($promoId, $limit = 20)
    {
        $db = promo_db();
        $promoId = (int)$promoId;
        $limit = max(1, (int)$limit);

        $sql = 'SELECT id, order_number, customer_name, customer_phone, total_amount, discount_value, payment_status, order_status, created_at
                FROM orders
                WHERE promo_code_id = ?
                ORDER BY id DESC
                LIMIT ?';
        $stmt = $db->prepare($sql);
        $stmt->bind_param('ii', $promoId, $limit);
        $stmt->execute();
        $rows = promo_fetch_all($stmt);
        $stmt->close();

        return $rows;
    }
}
