<?php
declare(strict_types=1);

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

$db = Database::getInstance();

$data = json_decode(file_get_contents('php://input'), true);

if (empty($data['dealer_id'])) {
    Response::error('dealer_id is required', 422);
}

$dealerId = (int)$data['dealer_id'];

/**
 * Role check: only Super Admin & Admin
 */
$stmt = $db->prepare("
    SELECT r.name
    FROM roles r
    JOIN employees e ON e.role_id = r.id
    WHERE e.id = :employee_id
");
$stmt->execute(['employee_id' => $_SESSION['employee_id']]);
$role = $stmt->fetch();

if (!$role || !in_array($role['name'], ['Super Admin', 'Admin'], true)) {
    Response::error('You are not authorized to approve dealers', 403);
}


/**
 * Fetch dealer
 */
$stmt = $db->prepare("
    SELECT id, status, approval_status, latitude, longitude
    FROM dealers
    WHERE id = :id
");
$stmt->execute(['id' => $dealerId]);
$dealer = $stmt->fetch();

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

if ($dealer['approval_status'] !== 'Pending') {
    Response::error('Dealer is not in pending state', 422);
}

/**
 * Validate location
 */
if (empty($dealer['latitude']) || empty($dealer['longitude'])) {
    Response::error('Dealer location is incomplete', 422);
}

/**
 * Validate images (at least one active)
 */
$stmt = $db->prepare("
    SELECT COUNT(*) FROM dealer_images
    WHERE dealer_id = :id AND status = 'Active'
");
$stmt->execute(['id' => $dealerId]);
if ((int)$stmt->fetchColumn() === 0) {
    Response::error('At least one dealer image is required for approval', 422);
}

/**
 * Validate SEO (meta title or description)
 */
$stmt = $db->prepare("
    SELECT meta_title, meta_description
    FROM dealer_seo
    WHERE dealer_id = :id
");
$stmt->execute(['id' => $dealerId]);
$seo = $stmt->fetch();

if (!$seo || (empty($seo['meta_title']) && empty($seo['meta_description']))) {
    Response::error('SEO meta title or description is required for approval', 422);
}

/**
 * Approve & publish
 */
$stmt = $db->prepare("
    UPDATE dealers
    SET
        approval_status = 'Approved',
        status = 'Active',
        approved_by = :approved_by,
        approved_at = NOW(),
        updated_at = NOW()
    WHERE id = :id
");

$stmt->execute([
    'approved_by' => $_SESSION['employee_id'],
    'id'          => $dealerId
]);

Logger::auth('Dealer approved', [
    'dealer_id' => $dealerId,
    'by'        => $_SESSION['employee_id']
]);

Response::success('Dealer approved and published successfully');
