<?php
/**
 * GET /api/requests/list.php
 * Public. Query params: status (default 'open'), category_id, search, scope=mine, page
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

$page = max(1, (int) ($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

$pdo = Database::connect();

$where = [];
$params = [];

if (($_GET['scope'] ?? '') === 'mine') {
    $userId = require_login();
    $where[] = 'ir.requester_id = ?';
    $params[] = $userId;
} else {
    $status = $_GET['status'] ?? 'open';
    if (in_array($status, ['open', 'fulfilled', 'cancelled'], true)) {
        $where[] = 'ir.status = ?';
        $params[] = $status;
    }
}

if (!empty($_GET['category_id'])) {
    $where[] = 'ir.category_id = ?';
    $params[] = (int) $_GET['category_id'];
}
if (!empty($_GET['search'])) {
    $where[] = 'ir.item_name LIKE ?';
    $params[] = '%' . $_GET['search'] . '%';
}

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

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM item_requests ir $whereSql");
$countStmt->execute($params);
$total = (int) $countStmt->fetchColumn();

$stmt = $pdo->prepare("
    SELECT ir.id, ir.item_name, ir.description, ir.desired_quantity, ir.status, ir.created_at,
           c.name AS category_name,
           COALESCE(pp.full_name, bp.business_name) AS requester_name
    FROM item_requests ir
    LEFT JOIN categories c ON c.id = ir.category_id
    JOIN users u ON u.id = ir.requester_id
    LEFT JOIN personal_profiles pp ON pp.user_id = u.id
    LEFT JOIN business_profiles bp ON bp.user_id = u.id
    $whereSql
    ORDER BY ir.created_at DESC
    LIMIT $perPage OFFSET $offset
");
$stmt->execute($params);

send_json(true, 'OK', [
    'requests' => $stmt->fetchAll(),
    'pagination' => ['page' => $page, 'per_page' => $perPage, 'total' => $total, 'total_pages' => (int) ceil($total / $perPage)],
]);
