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

$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$category = isset($_POST['category']) ? trim($_POST['category']) : '';

if (!$title || !$category) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

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

// Handle image upload
$new_image = null;
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
    $upload_dir = __DIR__ . '/assets/img/project/';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $file = $_FILES['image'];
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

    if (!in_array($file['type'], $allowed_types)) {
        echo json_encode(['success' => false, 'message' => 'Invalid file type']);
        exit;
    }

    if ($file['size'] > 5 * 1024 * 1024) {
        echo json_encode(['success' => false, 'message' => 'File too large']);
        exit;
    }

    $file_ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $new_filename = 'project_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $file_ext;
    $upload_path = $upload_dir . $new_filename;

    if (!move_uploaded_file($file['tmp_name'], $upload_path)) {
        echo json_encode(['success' => false, 'message' => 'Failed to upload image']);
        exit;
    }

    $new_image = 'assets/img/project/' . $new_filename;
} else {
    // Use default image if none provided
    $new_image = 'assets/img/project/project_default.jpg';
}

$content = file_get_contents($project_file);

// Find the insertion point: before "<!-- ARCHITECTURAL -->" comment
$insertion_pattern = '/(\s*<!-- ARCHITECTURAL -->)/';

$new_project_html = <<<HTML

                <!-- Project -->
                <div class="project-card">
                    <div class="card-image">
                        <img src="$new_image" alt="$title">
                    </div>
                    <div class="project-card-footer">
                        <span class="category">$category</span>
                        <h3 class="title">$title</h3>
                    </div>
                    <div class="project-content">
                        <span class="category">$category</span>
                        <h3 class="project-title"><a href="project-details.html">$title</a></h3>
                        <div class="project-actions">
                            <button class="project-popup-btn" onclick="openPopup('$new_image')">
                                <i class="far fa-plus"></i>
                            </button>
                            <a href="project-details.html" class="project-learn-btn">Learn More</a>
                        </div>
                    </div>
                </div>

HTML;

// Insert before the ARCHITECTURAL comment
if (preg_match($insertion_pattern, $content)) {
    $new_content = preg_replace($insertion_pattern, $new_project_html . "\n\n<!-- ARCHITECTURAL -->", $content);
} else {
    // Fallback: if pattern not found, append before testimonial section
    $fallback_pattern = '/(\s*<!-- Testimonial -->)/';
    if (preg_match($fallback_pattern, $content)) {
        $new_content = preg_replace($fallback_pattern, $new_project_html . "\n\n<!-- Testimonial -->", $content);
    } else {
        echo json_encode(['success' => false, 'message' => 'Could not find insertion point in project.php']);
        exit;
    }
}

if (file_put_contents($project_file, $new_content) !== false) {
    echo json_encode(['success' => true, 'message' => 'Project added successfully and project.php has been updated']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update project.php']);
}
?>
