<?php
session_start();

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$project_id = isset($_POST['project_id']) ? intval($_POST['project_id']) : 0;

if (!$project_id) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Project ID is required']);
    exit;
}

$index_file = __DIR__ . '/index.php';
if (!file_exists($index_file)) {
    echo json_encode(['success' => false, 'message' => 'Index file not found']);
    exit;
}

$content = file_get_contents($index_file);

// Find and delete the project by counting
$project_count = 0;
$found = false;
$image_to_delete = null;

// First, find the image to delete
preg_replace_callback(
    '/<div class="project-card"[^>]*>.*?<\/div>\s*(?=<div class="project-card"|<\/div>)/s',
    function($matches) use (&$project_count, $project_id, &$image_to_delete) {
        $project_count++;
        
        if ($project_count === $project_id) {
            if (preg_match('/<img src="([^"]+)"/', $matches[0], $img_matches)) {
                $image_to_delete = $img_matches[1];
            }
        }
        
        return $matches[0];
    },
    $content
);

// Reset counter and delete the project
$project_count = 0;
$new_content = preg_replace_callback(
    '/<div class="project-card"[^>]*>.*?<\/div>\s*(?=<div class="project-card"|<\/div>)/s',
    function($matches) use (&$project_count, $project_id, &$found) {
        $project_count++;
        
        if ($project_count === $project_id) {
            $found = true;
            return ''; // Delete this project
        }
        
        return $matches[0];
    },
    $content
);

if (!$found) {
    echo json_encode(['success' => false, 'message' => 'Project not found']);
    exit;
}

// Remove the image file if it exists
if ($image_to_delete) {
    $image_path = __DIR__ . '/' . $image_to_delete;
    if (file_exists($image_path) && strpos($image_to_delete, 'assets/img/project/') !== false) {
        @unlink($image_path);
    }
}

if (file_put_contents($index_file, $new_content) !== false) {
    echo json_encode(['success' => true, 'message' => 'Project deleted successfully and index.php changed']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update index.php']);
}
?>
