<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

/**
 * ----------------------------
 * Pagination params
 * ----------------------------
 */
$page  = max(1, (int) ($_GET['page'] ?? 1));
$limit = max(1, min(50, (int) ($_GET['limit'] ?? 10)));
$offset = ($page - 1) * $limit;

/**
 * ----------------------------
 * Filters
 * ----------------------------
 */
$status = $_GET['status'] ?? null;

$where = 'deleted_at IS NULL';
$params = [];

if ($status !== null) {
    $where .= ' AND status = :status';
    $params['status'] = $status;
}

/**
 * ----------------------------
 * Total count
 * ----------------------------
 */
$countStmt = $db->prepare("
    SELECT COUNT(*) 
    FROM offers 
    WHERE {$where}
");
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();

/**
 * ----------------------------
 * Fetch data
 * ----------------------------
 */
$stmt = $db->prepare("
    SELECT
        id,
        title,
        short_description,
        offer_price,
        desktop_image,
        mobile_image,
        redirect_url,
        status,
        start_date,
        end_date,
        created_at
    FROM offers
    WHERE {$where}
    ORDER BY created_at DESC
    LIMIT :limit OFFSET :offset
");

foreach ($params as $key => $value) {
    $stmt->bindValue(':' . $key, $value);
}

$stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);

$stmt->execute();
$offers = $stmt->fetchAll();

/**
 * ----------------------------
 * Response
 * ----------------------------
 */
Response::success('Offers fetched successfully', [
    'items' => $offers,
    'pagination' => [
        'page'  => $page,
        'limit'=> $limit,
        'total'=> $total
    ]
]);
