<?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");
}

if (isset($_POST['id'])) {
    $id = (int)$_POST['id'];

    $images = [];
    $row = $conn->query("SELECT image FROM projects WHERE id=$id")->fetch_assoc();
    if (!empty($row['image'])) {
        $images[] = $row['image'];
    }

    $imgTable = $conn->query("SHOW TABLES LIKE 'project_images'");
    if ($imgTable && $imgTable->num_rows > 0) {
        $res = $conn->query("SELECT image FROM project_images WHERE project_id=$id");
        while ($res && ($r = $res->fetch_assoc())) {
            if (!empty($r['image'])) {
                $images[] = $r['image'];
            }
        }
        $conn->query("DELETE FROM project_images WHERE project_id=$id");
    }

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

    foreach ($images as $img) {
        $fileName = basename(str_replace(['../', '..\\'], '', $img));
        $path = "../../../files/" . $fileName;
        if (is_file($path)) {
            unlink($path);
        }
    }

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