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

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

$content = file_get_contents($project_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"|<!-- ARCHITECTURAL -->|<!-- Testimonial -->)/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"|<!-- ARCHITECTURAL -->|<!-- Testimonial -->)/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($project_file, $new_content) !== false) {
    echo json_encode(['success' => true, 'message' => 'Project deleted successfully and project.php has been changed']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update project.php']);
}
?>
