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

$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 update the project by counting
$project_count = 0;
$found = false;
$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, $title, $category, &$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 = $current_image;
            } else {
                $image_to_use = '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;
}

// Handle image upload if provided
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;
    
    // Update the image in the content
    $project_count = 0;
    $new_content = preg_replace_callback(
        '/<div class="project-card"[^>]*>.*?<img src="([^"]+)"/',
        function($matches) use (&$project_count, $project_id, $new_image) {
            $project_count++;
            if ($project_count === $project_id) {
                return str_replace($matches[1], $new_image, $matches[0]);
            }
            return $matches[0];
        },
        $new_content
    );
}

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