<?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 || !isset($_FILES['image'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

// Handle file upload
$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;
}

// Read index.php
$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);

// Create new project card HTML that matches index.php structure
$new_project = <<<HTML
                <!-- Project -->
                <div class="project-card">
                    <div class="card-image">
                        <img src="assets/img/project/$new_filename" 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('assets/img/project/$new_filename')">
                                <i class="far fa-plus"></i>
                            </button>
                            <a href="project-details.html" class="project-learn-btn">Learn More</a>
                        </div>
                    </div>
                </div>

HTML;

// Find the projects-grid closing div and insert before it
$pattern = '/<\/div>\s*<\/div>\s*<!-- ABOUT US -->/';
$replacement = $new_project . "            </div>\n        </div>\n    </section>\n\n    <!-- ABOUT US -->";

if (preg_match($pattern, $content)) {
    $new_content = preg_replace($pattern, $replacement, $content, 1);
} else {
    // Fallback: find and replace before closing the projects-grid
    $pattern = '/(<div class="projects-grid"[^>]*>.*)([\r\n\s]*<\/div>[\r\n\s]*<\/div>[\r\n\s]*<\/section>[\r\n\s]*<!-- ABOUT US -->)/s';
    $new_content = preg_replace_callback($pattern, function($matches) use ($new_project) {
        return $matches[1] . $new_project . $matches[2];
    }, $content);
}

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