<?php
declare(strict_types=1);

require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

session_name(SESSION_NAME);
session_start();

$db = Database::getInstance();

/**
 * Detect backend (logged-in admin)
 */
$isBackend = isset($_SESSION['employee_id']) &&
             in_array($_SESSION['role'] ?? '', ['Admin', 'Super Admin'], true);

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

/**
 * Filters (shared)
 */
$filters = [
    'state_id'        => $_GET['state_id'] ?? null,
    'city_id'         => $_GET['city_id'] ?? null,
    'dealer_type_id'  => $_GET['dealer_type_id'] ?? null,
    'search'          => $_GET['search'] ?? null,
];

/**
 * Backend-only filters
 */
if ($isBackend) {
    $filters['status']          = $_GET['status'] ?? null;
    $filters['approval_status'] = $_GET['approval_status'] ?? null;
    $filters['cst_id']          = $_GET['cst_id'] ?? null;
}

$sql = "
FROM dealers d
JOIN dealer_types dt ON dt.id = d.dealer_type_id
JOIN states s ON s.id = d.state_id
JOIN cities c ON c.id = d.city_id
LEFT JOIN dealer_images di 
    ON di.dealer_id = d.id AND di.is_primary = 1 AND di.status = 'Active'
WHERE 1=1
";

$params = [];

/**
 * Frontend restriction
 */
if (!$isBackend) {
    $sql .= "
        AND d.status = 'Active'
        AND d.approval_status = 'Approved'
    ";
}

/**
 * Apply filters
 */
foreach ($filters as $key => $value) {
    if ($value === null || $value === '') {
        continue;
    }

    switch ($key) {
        case 'state_id':
        case 'city_id':
        case 'dealer_type_id':
        case 'cst_id':
            $sql .= " AND d.$key = :$key ";
            $params[$key] = (int)$value;
            break;

        case 'search':
            $sql .= " AND d.dealer_name LIKE :search ";
            $params['search'] = '%' . trim($value) . '%';
            break;

        case 'status':
        case 'approval_status':
            if ($isBackend) {
                $sql .= " AND d.$key = :$key ";
                $params[$key] = $value;
            }
            break;
    }
}

/**
 * Count
 */
$countStmt = $db->prepare("SELECT COUNT(*) $sql");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();

/**
 * Data query
 */
$dataSql = "
SELECT
    d.id,
    d.dealer_name,
    d.slug,
    d.status,
    d.approval_status,
    d.created_at,

    dt.dealer_type,
    s.state_name,
    c.city_name,
    di.image_path AS primary_image
$sql
ORDER BY d.display_order ASC, d.created_at DESC
LIMIT :limit OFFSET :offset
";

$stmt = $db->prepare($dataSql);

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

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

$stmt->execute();

Response::success('Dealer list fetched successfully', [
    'mode' => $isBackend ? 'backend' : 'frontend',
    'pagination' => [
        'page'  => $page,
        'limit' => $limit,
        'total' => $total
    ],
    'items' => $stmt->fetchAll()
]);
