<?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']) || empty($data['rejection_reason'])) {
    Response::error('dealer_id and rejection_reason are required', 422);
}

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

/**
 * 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 reject dealers', 403);
}

/**
 * Fetch dealer
 */
$stmt = $db->prepare("
    SELECT id, approval_status
    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('Only pending dealers can be rejected', 422);
}

/**
 * Reject dealer
 */
$stmt = $db->prepare("
    UPDATE dealers
    SET
        approval_status  = 'Rejected',
        status           = 'Draft',
        rejection_reason = :reason,
        rejected_by      = :rejected_by,
        rejected_at      = NOW(),
        updated_at       = NOW()
    WHERE id = :id
");

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

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

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