<?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();

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

if (empty($data['dealer_id']) || empty($data['status'])) {
    Response::error('dealer_id and status are required', 422);
}

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

/**
 * Allowed statuses
 */
$allowedStatuses = ['Active', 'Inactive', 'Draft'];
if (!in_array($status, $allowedStatuses, true)) {
    Response::error('Invalid status value', 422);
}

/**
 * Role check (Admin / Super 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 update dealer status', 403);
}

/**
 * Ensure dealer exists
 */
$stmt = $db->prepare("SELECT id FROM dealers WHERE id = :id");
$stmt->execute(['id' => $dealerId]);

if (!$stmt->fetch()) {
    Response::error('Dealer not found', 404);
}

/**
 * Update status
 */
$stmt = $db->prepare("
    UPDATE dealers
    SET status = :status,
        updated_at = NOW()
    WHERE id = :id
");
$stmt->execute([
    'status' => $status,
    'id'     => $dealerId
]);

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

Response::success('Dealer status updated successfully');
