<?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: Super Admin / Admin only
 */
$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 deactivate dealers', 403);
}

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

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

if ($dealer['status'] === 'InActive') {
    Response::error('Dealer is already deactivated', 422);
}

/**
 * Deactivate dealer (soft delete)
 */
$stmt = $db->prepare("
    UPDATE dealers
    SET
        status = 'InActive',
        approval_status = 'Rejected',
        updated_by = :updated_by,
        updated_at = NOW()
    WHERE id = :id
");

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

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

Response::success('Dealer deactivated successfully');
