<?php
if (!function_exists('offers_db')) {
    function offers_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;
        return null;
    }
}

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

if (!function_exists('offers_has_table')) {
    function offers_has_table(mysqli $conn, string $tableName): bool {
        $tableName = $conn->real_escape_string($tableName);
        $sql = "SHOW TABLES LIKE '{$tableName}'";
        $res = $conn->query($sql);
        return $res && $res->num_rows > 0;
    }
}

if (!function_exists('offers_get_companies_table')) {
    function offers_get_companies_table(mysqli $conn): ?string {
        if (offers_has_table($conn, 'companies')) return 'companies';
        if (offers_has_table($conn, 'brands')) return 'brands';
        return null;
    }
}

if (!function_exists('offers_get_product_company_column')) {
    function offers_get_product_company_column(mysqli $conn): ?string {
        $res = $conn->query("SHOW COLUMNS FROM products");
        if (!$res) return null;
        while ($row = $res->fetch_assoc()) {
            $field = strtolower($row['Field']);
            if ($field === 'company_id') return 'company_id';
            if ($field === 'brand_id') return 'brand_id';
        }
        return null;
    }
}

if (!function_exists('offers_format_money')) {
    function offers_format_money($value): string {
        if ($value === null || $value === '') return '-';
        return number_format((float)$value, 0) . ' IQD';
    }
}

if (!function_exists('offers_type_label')) {
    function offers_type_label(string $type): string {
        $map = [
            'individual' => 'فردي',
            'bundle' => 'باقة',
            'quantity' => 'كمية',
            'company' => 'شركة/براند',
        ];
        return $map[$type] ?? $type;
    }
}

if (!function_exists('offers_status_label')) {
    function offers_status_label($status): string {
        return ((int)$status === 1) ? 'مفعّل' : 'معطّل';
    }
}

if (!function_exists('offers_status_class')) {
    function offers_status_class($status): string {
        return ((int)$status === 1) ? 'is-active' : 'is-inactive';
    }
}

if (!function_exists('offers_flash_set')) {
    function offers_flash_set(string $type, string $message): void {
        if (session_status() !== PHP_SESSION_ACTIVE) @session_start();
        $_SESSION['offers_flash'] = ['type' => $type, 'message' => $message];
    }
}

if (!function_exists('offers_flash_get')) {
    function offers_flash_get(): ?array {
        if (session_status() !== PHP_SESSION_ACTIVE) @session_start();
        if (!isset($_SESSION['offers_flash'])) return null;
        $flash = $_SESSION['offers_flash'];
        unset($_SESSION['offers_flash']);
        return $flash;
    }
}

if (!function_exists('offers_fetch_products')) {
    function offers_fetch_products(mysqli $conn): array {
        $products = [];
        $companyColumn = offers_get_product_company_column($conn);
        $companyTable = offers_get_companies_table($conn);
        $companyJoin = '';
        $companySelect = "'' AS company_name";
        if ($companyColumn && $companyTable) {
            $companyJoin = " LEFT JOIN {$companyTable} c ON c.id = p.{$companyColumn} ";
            $companySelect = "COALESCE(c.name, '') AS company_name";
        }
        $sql = "SELECT p.id, p.name, COALESCE(p.price, 0) AS price, {$companySelect}
                FROM products p
                {$companyJoin}
                ORDER BY p.name ASC";
        $res = $conn->query($sql);
        if ($res) {
            while ($row = $res->fetch_assoc()) $products[] = $row;
        }
        return $products;
    }
}

if (!function_exists('offers_fetch_companies')) {
    function offers_fetch_companies(mysqli $conn): array {
        $table = offers_get_companies_table($conn);
        if (!$table) return [];
        $items = [];
        $res = $conn->query("SELECT id, name FROM {$table} ORDER BY name ASC");
        if ($res) {
            while ($row = $res->fetch_assoc()) $items[] = $row;
        }
        return $items;
    }
}

if (!function_exists('offers_get_product_map')) {
    function offers_get_product_map(mysqli $conn): array {
        $map = [];
        foreach (offers_fetch_products($conn) as $row) {
            $map[(int)$row['id']] = $row;
        }
        return $map;
    }
}

if (!function_exists('offers_get_company_map')) {
    function offers_get_company_map(mysqli $conn): array {
        $map = [];
        foreach (offers_fetch_companies($conn) as $row) {
            $map[(int)$row['id']] = $row;
        }
        return $map;
    }
}

if (!function_exists('offers_now')) {
    function offers_now(): string {
        return date('Y-m-d H:i:s');
    }
}

if (!function_exists('offers_parse_datetime')) {
    function offers_parse_datetime(?string $value): ?string {
        $value = trim((string)$value);
        if ($value === '') return null;
        $value = str_replace('T', ' ', $value);
        if (strlen($value) === 16) $value .= ':00';
        return $value;
    }
}

if (!function_exists('offers_collect_items_from_post')) {
    function offers_collect_items_from_post(array $productMap): array {
        $productIds = $_POST['bundle_product_id'] ?? [];
        $qtys = $_POST['bundle_qty'] ?? [];
        $items = [];
        if (!is_array($productIds) || !is_array($qtys)) return $items;
        foreach ($productIds as $idx => $productId) {
            $productId = (int)$productId;
            $qty = isset($qtys[$idx]) ? (int)$qtys[$idx] : 0;
            if ($productId <= 0 || $qty <= 0 || !isset($productMap[$productId])) continue;
            $price = (float)$productMap[$productId]['price'];
            $items[] = [
                'product_id' => $productId,
                'qty' => $qty,
                'unit_price' => $price,
                'line_total' => $price * $qty,
            ];
        }
        return $items;
    }
}

if (!function_exists('offers_bundle_total')) {
    function offers_bundle_total(array $items): float {
        $total = 0.0;
        foreach ($items as $item) $total += (float)$item['line_total'];
        return $total;
    }
}

if (!function_exists('offers_dashboard_counts')) {
    function offers_dashboard_counts(mysqli $conn): array {
        $tables = [
            'individual' => 'individual_offers',
            'bundle' => 'bundle_offers',
            'quantity' => 'quantity_offers',
            'company' => 'company_offers',
        ];
        $counts = [
            'all' => 0,
            'active' => 0,
            'individual' => 0,
            'bundle' => 0,
            'quantity' => 0,
            'company' => 0,
        ];
        foreach ($tables as $type => $table) {
            $res = $conn->query("SELECT COUNT(*) AS c, SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS a FROM {$table}");
            if ($res && ($row = $res->fetch_assoc())) {
                $counts[$type] = (int)$row['c'];
                $counts['all'] += (int)$row['c'];
                $counts['active'] += (int)$row['a'];
            }
        }
        return $counts;
    }
}

if (!function_exists('offers_fetch_all')) {
    function offers_fetch_all(mysqli $conn, array $filters = []): array {
        $productMap = offers_get_product_map($conn);
        $companyMap = offers_get_company_map($conn);

        $all = [];

        $sql1 = "SELECT id, title, product_id, old_price, new_price, start_date, end_date, status, notes, created_at, updated_at
                 FROM individual_offers";
        if ($res = $conn->query($sql1)) {
            while ($row = $res->fetch_assoc()) {
                $row['type'] = 'individual';
                $row['product_name'] = $productMap[(int)$row['product_id']]['name'] ?? ('#' . $row['product_id']);
                $row['company_name'] = $productMap[(int)$row['product_id']]['company_name'] ?? '';
                $all[] = $row;
            }
        }

        $sql2 = "SELECT id, title, item_count, old_price_total, new_price_total, start_date, end_date, status, notes, created_at, updated_at
                 FROM bundle_offers";
        if ($res = $conn->query($sql2)) {
            while ($row = $res->fetch_assoc()) {
                $row['type'] = 'bundle';
                $row['product_name'] = ($row['item_count'] ?? 0) . ' عنصر';
                $row['old_price'] = $row['old_price_total'];
                $row['new_price'] = $row['new_price_total'];
                $row['company_name'] = '';
                $all[] = $row;
            }
        }

        $sql3 = "SELECT id, title, product_id, required_qty, old_price_total, new_price_total, start_date, end_date, status, notes, created_at, updated_at
                 FROM quantity_offers";
        if ($res = $conn->query($sql3)) {
            while ($row = $res->fetch_assoc()) {
                $row['type'] = 'quantity';
                $baseName = $productMap[(int)$row['product_id']]['name'] ?? ('#' . $row['product_id']);
                $row['product_name'] = $baseName . ' × ' . (int)$row['required_qty'];
                $row['old_price'] = $row['old_price_total'];
                $row['new_price'] = $row['new_price_total'];
                $row['company_name'] = $productMap[(int)$row['product_id']]['company_name'] ?? '';
                $all[] = $row;
            }
        }

        $sql4 = "SELECT id, title, company_id, discount_type, discount_value, start_date, end_date, status, notes, created_at, updated_at
                 FROM company_offers";
        if ($res = $conn->query($sql4)) {
            while ($row = $res->fetch_assoc()) {
                $row['type'] = 'company';
                $row['product_name'] = $companyMap[(int)$row['company_id']]['name'] ?? ('#' . $row['company_id']);
                $row['old_price'] = null;
                $row['new_price'] = ($row['discount_type'] === 'percent')
                    ? ((float)$row['discount_value'] . '%')
                    : ('-' . offers_format_money($row['discount_value']));
                $row['company_name'] = $row['product_name'];
                $all[] = $row;
            }
        }

        $type = trim((string)($filters['type'] ?? ''));
        $status = (string)($filters['status'] ?? '');
        $search = trim((string)($filters['search'] ?? ''));

        $all = array_values(array_filter($all, function ($row) use ($type, $status, $search) {
            if ($type !== '' && ($row['type'] ?? '') !== $type) return false;
            if ($status !== '' && (string)($row['status'] ?? '') !== $status) return false;
            if ($search !== '') {
                $haystack = mb_strtolower(
                    implode(' ', [
                        $row['title'] ?? '',
                        $row['product_name'] ?? '',
                        $row['company_name'] ?? '',
                        $row['notes'] ?? '',
                    ]),
                    'UTF-8'
                );
                if (mb_strpos($haystack, mb_strtolower($search, 'UTF-8')) === false) return false;
            }
            return true;
        }));

        usort($all, function ($a, $b) {
            return strcmp((string)($b['created_at'] ?? ''), (string)($a['created_at'] ?? ''));
        });

        return $all;
    }
}

if (!function_exists('offers_find')) {
    function offers_find(mysqli $conn, string $type, int $id): ?array {
        if ($id <= 0) return null;
        $productMap = offers_get_product_map($conn);
        $companyMap = offers_get_company_map($conn);

        switch ($type) {
            case 'individual':
                $stmt = $conn->prepare("SELECT * FROM individual_offers WHERE id = ? LIMIT 1");
                break;
            case 'bundle':
                $stmt = $conn->prepare("SELECT * FROM bundle_offers WHERE id = ? LIMIT 1");
                break;
            case 'quantity':
                $stmt = $conn->prepare("SELECT * FROM quantity_offers WHERE id = ? LIMIT 1");
                break;
            case 'company':
                $stmt = $conn->prepare("SELECT * FROM company_offers WHERE id = ? LIMIT 1");
                break;
            default:
                return null;
        }
        if (!$stmt) return null;
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $res = $stmt->get_result();
        $item = $res ? $res->fetch_assoc() : null;
        $stmt->close();
        if (!$item) return null;

        $item['type'] = $type;
        if ($type === 'individual') {
            $item['product_name'] = $productMap[(int)$item['product_id']]['name'] ?? ('#' . $item['product_id']);
        } elseif ($type === 'quantity') {
            $baseName = $productMap[(int)$item['product_id']]['name'] ?? ('#' . $item['product_id']);
            $item['product_name'] = $baseName . ' × ' . (int)$item['required_qty'];
        } elseif ($type === 'company') {
            $item['company_name'] = $companyMap[(int)$item['company_id']]['name'] ?? ('#' . $item['company_id']);
        }
        return $item;
    }
}

if (!function_exists('offers_fetch_bundle_items')) {
    function offers_fetch_bundle_items(mysqli $conn, int $offerId): array {
        $rows = [];
        if ($offerId <= 0) return $rows;
        $sql = "SELECT oi.*, p.name AS product_name
                FROM bundle_offer_items oi
                LEFT JOIN products p ON p.id = oi.product_id
                WHERE oi.bundle_offer_id = ?
                ORDER BY oi.id ASC";
        $stmt = $conn->prepare($sql);
        if (!$stmt) return $rows;
        $stmt->bind_param('i', $offerId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($res && ($row = $res->fetch_assoc())) $rows[] = $row;
        $stmt->close();
        return $rows;
    }
}

if (!function_exists('offers_delete')) {
    function offers_delete(mysqli $conn, string $type, int $id): bool {
        if ($type === 'bundle') {
            $stmtItems = $conn->prepare("DELETE FROM bundle_offer_items WHERE bundle_offer_id = ?");
            if ($stmtItems) {
                $stmtItems->bind_param('i', $id);
                $stmtItems->execute();
                $stmtItems->close();
            }
        }
        $tableMap = [
            'individual' => 'individual_offers',
            'bundle' => 'bundle_offers',
            'quantity' => 'quantity_offers',
            'company' => 'company_offers',
        ];
        if (!isset($tableMap[$type])) return false;
        $stmt = $conn->prepare("DELETE FROM {$tableMap[$type]} WHERE id = ?");
        if (!$stmt) return false;
        $stmt->bind_param('i', $id);
        $ok = $stmt->execute();
        $stmt->close();
        return $ok;
    }
}

if (!function_exists('offers_toggle')) {
    function offers_toggle(mysqli $conn, string $type, int $id): bool {
        $tableMap = [
            'individual' => 'individual_offers',
            'bundle' => 'bundle_offers',
            'quantity' => 'quantity_offers',
            'company' => 'company_offers',
        ];
        if (!isset($tableMap[$type])) return false;
        $stmt = $conn->prepare("UPDATE {$tableMap[$type]} SET status = IF(status = 1, 0, 1), updated_at = NOW() WHERE id = ?");
        if (!$stmt) return false;
        $stmt->bind_param('i', $id);
        $ok = $stmt->execute();
        $stmt->close();
        return $ok;
    }
}

if (!function_exists('offers_validate_post')) {
    function offers_validate_post(mysqli $conn, string $type): array {
        $errors = [];
        $data = [
            'type' => $type,
            'title' => trim((string)($_POST['title'] ?? '')),
            'start_date' => offers_parse_datetime($_POST['start_date'] ?? ''),
            'end_date' => offers_parse_datetime($_POST['end_date'] ?? ''),
            'status' => isset($_POST['status']) ? (int)$_POST['status'] : 1,
            'notes' => trim((string)($_POST['notes'] ?? '')),
        ];

        $productMap = offers_get_product_map($conn);

        if ($data['title'] === '') $errors[] = 'عنوان العرض مطلوب.';

        if ($type === 'individual') {
            $data['product_id'] = (int)($_POST['product_id'] ?? 0);
            $data['old_price'] = isset($productMap[$data['product_id']]) ? (float)$productMap[$data['product_id']]['price'] : 0.0;
            $data['new_price'] = (float)($_POST['new_price'] ?? 0);
            if ($data['product_id'] <= 0) $errors[] = 'اختر المنتج.';
            if ($data['new_price'] <= 0) $errors[] = 'السعر الجديد يجب أن يكون أكبر من صفر.';
            if ($data['old_price'] > 0 && $data['new_price'] >= $data['old_price']) $errors[] = 'السعر الجديد يجب أن يكون أقل من السعر الأصلي.';
        } elseif ($type === 'bundle') {
            $items = offers_collect_items_from_post($productMap);
            $data['items'] = $items;
            $data['item_count'] = count($items);
            $data['old_price_total'] = offers_bundle_total($items);
            $data['new_price_total'] = (float)($_POST['new_price_total'] ?? 0);
            if ($data['item_count'] <= 0) $errors[] = 'أضف عنصر واحد على الأقل داخل الباقة.';
            if ($data['new_price_total'] <= 0) $errors[] = 'السعر النهائي للباقة يجب أن يكون أكبر من صفر.';
            if ($data['old_price_total'] > 0 && $data['new_price_total'] >= $data['old_price_total']) $errors[] = 'سعر الباقة يجب أن يكون أقل من مجموع أسعارها الأصلي.';
        } elseif ($type === 'quantity') {
            $data['product_id'] = (int)($_POST['product_id'] ?? 0);
            $data['required_qty'] = (int)($_POST['required_qty'] ?? 0);
            $single = isset($productMap[$data['product_id']]) ? (float)$productMap[$data['product_id']]['price'] : 0.0;
            $data['old_price_total'] = $single * max(0, $data['required_qty']);
            $data['new_price_total'] = (float)($_POST['new_price_total'] ?? 0);
            if ($data['product_id'] <= 0) $errors[] = 'اختر المنتج.';
            if ($data['required_qty'] < 2) $errors[] = 'كمية العرض يجب أن تكون 2 أو أكثر.';
            if ($data['new_price_total'] <= 0) $errors[] = 'السعر النهائي يجب أن يكون أكبر من صفر.';
            if ($data['old_price_total'] > 0 && $data['new_price_total'] >= $data['old_price_total']) $errors[] = 'السعر النهائي يجب أن يكون أقل من السعر الأصلي الإجمالي.';
        } elseif ($type === 'company') {
            $data['company_id'] = (int)($_POST['company_id'] ?? 0);
            $data['discount_type'] = ($_POST['discount_type'] ?? 'percent') === 'amount' ? 'amount' : 'percent';
            $data['discount_value'] = (float)($_POST['discount_value'] ?? 0);
            if ($data['company_id'] <= 0) $errors[] = 'اختر الشركة/البراند.';
            if ($data['discount_value'] <= 0) $errors[] = 'قيمة الخصم يجب أن تكون أكبر من صفر.';
            if ($data['discount_type'] === 'percent' && $data['discount_value'] >= 100) $errors[] = 'نسبة الخصم يجب أن تكون أقل من 100%.';
        }

        if ($data['start_date'] && $data['end_date'] && $data['end_date'] < $data['start_date']) {
            $errors[] = 'تاريخ نهاية العرض يجب أن يكون بعد البداية.';
        }

        return [$data, $errors];
    }
}
?>
<?php
if (!function_exists('offers_table_has_column')) {
    function offers_table_has_column(mysqli $conn, string $table, string $column): bool {
        static $cache = [];
        $key = $table . '.' . $column;
        if (array_key_exists($key, $cache)) return $cache[$key];
        $table = $conn->real_escape_string($table);
        $column = $conn->real_escape_string($column);
        $res = $conn->query("SHOW COLUMNS FROM `{$table}` LIKE '{$column}'");
        $cache[$key] = $res && $res->num_rows > 0;
        if ($res instanceof mysqli_result) $res->close();
        return $cache[$key];
    }
}

if (!function_exists('offers_fetch_products_with_variants')) {
    function offers_fetch_products_with_variants(mysqli $conn): array {
        $products = [];
        $res = $conn->query("SELECT id, name, price, brand_part FROM products WHERE status = 1 ORDER BY name ASC");
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                $row['variants'] = [];
                $stmt = $conn->prepare("SELECT id, variant_name, price, stock_qty FROM product_variants WHERE product_id = ? AND status = 1 ORDER BY sort_order ASC, id ASC");
                $stmt->bind_param('i', $row['id']);
                $stmt->execute();
                $vr = $stmt->get_result();
                while ($v = $vr->fetch_assoc()) {
                    $row['variants'][] = $v;
                }
                $stmt->close();
                $products[] = $row;
            }
            $res->close();
        }
        return $products;
    }
}
