<?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;
$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$category = isset($_POST['category']) ? trim($_POST['category']) : '';

if (!$project_id || !$title || !$category) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    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);

// Handle image upload if provided
$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;
}

// Find the project by counting and update it
$project_count = 0;
$found = false;
$new_content = preg_replace_callback(
    '/<div class="project-card"[^>]*>.*?<\/div>\s*(?=<div class="project-card"|<\/div>)/s',
    function($matches) use (&$project_count, $project_id, $title, $category, $new_image, &$found) {
        $project_count++;
        
        if ($project_count === $project_id) {
            $found = true;
            // Extract current image to replace
            if (preg_match('/<img src="([^"]+)"/', $matches[0], $img_matches)) {
                $current_image = $img_matches[1];
                $image_to_use = $new_image ?: $current_image;
            } else {
                $image_to_use = $new_image ?: 'assets/img/project/project_default.jpg';
            }
            
            // Create updated project card
            return <<<HTML
<div class="project-card">
                    <div class="card-image">
                        <img src="$image_to_use" 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('$image_to_use')">
                                <i class="far fa-plus"></i>
                            </button>
                            <a href="project-details.html" class="project-learn-btn">Learn More</a>
                        </div>
                    </div>
                </div>

HTML;
        }
        
        return $matches[0];
    },
    $content
);

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

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