<?php
declare(strict_types=1);

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

session_start(); // needed to detect backend session

$db = Database::getInstance();

/**
 * Inputs
 */
$dealerId = isset($_GET['id']) ? (int)$_GET['id'] : null;
$slug     = isset($_GET['slug']) ? trim($_GET['slug']) : null;

if (!$dealerId && !$slug) {
    Response::error('Dealer id or slug is required', 422);
}

/**
 * Detect backend (admin logged in)
 */
$isBackend = isset($_SESSION['employee_id']);

/**
 * Base query
 */
$sql = "
SELECT
    d.id,
    d.dealer_name,
    d.slug,
    d.contact_person,
    d.email,
    d.phone,
    d.alt_phone,
    d.address_line1,
    d.address_line2,
    d.pincode,
    d.latitude,
    d.longitude,
    d.dealer_details,
    d.status,
    d.approval_status,
    d.content_status,
    d.display_order,
    d.created_at,

    dt.id   AS dealer_type_id,
    dt.dealer_type,

    cst.id  AS cst_id,
    cst.name AS cst_name,
    cst.phone AS cst_phone,
    cst.email AS cst_email,

    s.id AS state_id,
    s.state_name,

    c.id AS city_id,
    c.city_name
FROM dealers d
JOIN dealer_types dt ON dt.id = d.dealer_type_id
JOIN cst_managers cst ON cst.id = d.cst_id
JOIN states s ON s.id = d.state_id
JOIN cities c ON c.id = d.city_id
";

/**
 * WHERE conditions + params
 */
$params = [];

if ($dealerId !== null) {
    $sql .= " WHERE d.id = :id ";
    $params['id'] = $dealerId;
} else {
    $sql .= " WHERE d.slug = :slug ";
    $params['slug'] = $slug;

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

$stmt = $db->prepare($sql);
$stmt->execute($params);

$dealer = $stmt->fetch();

if (!$dealer) {
    Response::error('Dealer not found', 404);
}

/**
 * Fetch dealer images
 */
$imgStmt = $db->prepare("
    SELECT
        image_path,
        alt_text,
        caption,
        is_primary,
        sort_order
    FROM dealer_images
    WHERE dealer_id = :dealer_id
      AND status = 'Active'
    ORDER BY is_primary DESC, sort_order ASC
");
$imgStmt->execute(['dealer_id' => $dealer['id']]);
$dealer['images'] = $imgStmt->fetchAll();

/**
 * Fetch SEO data
 */
$seoStmt = $db->prepare("
    SELECT
        meta_title,
        meta_keywords,
        meta_description,
        seo_schema,
        ai_seo_content
    FROM dealer_seo
    WHERE dealer_id = :dealer_id
");
$seoStmt->execute(['dealer_id' => $dealer['id']]);
$dealer['seo'] = $seoStmt->fetch() ?: (object)[];

Response::success('Dealer fetched successfully', $dealer);
