<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../security/auth_guard_api.php';
require_once __DIR__ . '/../../security/csrf_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 */
$stmt = $db->prepare("
    SELECT r.name
    FROM roles r
    JOIN employees e ON e.role_id = r.id
    WHERE e.id = :eid
");
$stmt->execute(['eid' => $_SESSION['employee_id']]);
$role = $stmt->fetch();

if (!$role || $role['name'] !== 'Super Admin') {
    Response::error('Only Super Admin can delete dealer', 403);
}

try {
    $db->beginTransaction();

    /* CHECK DEALER */
    $stmt = $db->prepare("SELECT id FROM dealers WHERE id = :id");
    $stmt->execute(['id' => $dealerId]);
    if (!$stmt->fetch()) {
        throw new Exception('Dealer not found');
    }

    /* DELETE IMAGES (FILES) */
    $stmt = $db->prepare("SELECT image_path FROM dealer_images WHERE dealer_id = :id");
    $stmt->execute(['id' => $dealerId]);

    foreach ($stmt->fetchAll() as $img) {
        $path = BASE_PATH . '/' . ltrim($img['image_path'], '/');
        if (is_file($path) && is_writable($path)) {
            unlink($path);
        }
    }

    /* DELETE DB RECORDS */
    $db->prepare("DELETE FROM dealer_images WHERE dealer_id = :id")->execute(['id'=>$dealerId]);
    $db->prepare("DELETE FROM dealer_seo WHERE dealer_id = :id")->execute(['id'=>$dealerId]);
    $db->prepare("DELETE FROM dealers WHERE id = :id")->execute(['id'=>$dealerId]);

    $db->commit();

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

    Response::success('Dealer permanently deleted');

} catch (Throwable $e) {
    if ($db->inTransaction()) {
        $db->rollBack();
    }
    Logger::error('Dealer delete failed', ['error'=>$e->getMessage()]);
    Response::error('Failed to delete dealer', 500);
}
