<?php
include "../../includes/db.php";
include "../../includes/auth.php";

$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
if ($isAjax) {
    header("Content-Type: application/json");
}

$id = 0;
if (isset($_POST['id'])) {
    $id = (int)$_POST['id'];
} elseif (isset($_GET['id'])) {
    $id = (int)$_GET['id'];
}

$certType = $_POST['type'] ?? ($_GET['type'] ?? 'real');
$certType = $certType === 'automotive' ? 'automotive' : 'real';
$tableName = $certType === 'automotive' ? 'automotive_certifications' : 'certifications';

if ($id > 0) {
    $image = '';
    $imageCol = $conn->query("SHOW COLUMNS FROM $tableName LIKE 'image'");
    if ($imageCol && $imageCol->num_rows > 0) {
        $row = $conn->query("SELECT image FROM $tableName WHERE id=$id")->fetch_assoc();
        $image = $row['image'] ?? '';
    }

    $conn->query("DELETE FROM $tableName WHERE id=$id");

    if (!empty($image)) {
        $fileName = basename(str_replace(['../', '..\\'], '', $image));
        $rootPath = "../../../files/" . $fileName;
        $adminPath = "../../files/" . $fileName;
        if (is_file($rootPath)) {
            unlink($rootPath);
        }
        if (is_file($adminPath)) {
            unlink($adminPath);
        }
    }

    if ($conn->affected_rows > 0) {
        if ($isAjax) {
            echo json_encode(['status' => 'success']);
        } else {
            header("Location: certification.php?deleted=1");
        }
    } else {
        if ($isAjax) {
            echo json_encode(['status' => 'error', 'message' => 'Certification not found or already deleted.']);
        } else {
            header("Location: certification.php?deleted=0");
        }
    }
} else {
    if ($isAjax) {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Missing id.']);
    } else {
        header("Location: certification.php?deleted=0");
    }
}
