<?php
/**
 * Projects API Endpoint
 * GET: Return all projects ordered by createdAt desc, include edits
 * POST: Create new project
 */

require_once __DIR__ . '/../includes/Database.php';

header('Content-Type: application/json; charset=utf-8');

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    try {
        $db = Database::getInstance();

        // Get all projects
        $stmt = $db->query("SELECT * FROM PhotoProject ORDER BY createdAt DESC");
        $projects = $stmt->fetchAll();

        // Get edits for each project
        foreach ($projects as &$project) {
            $editStmt = $db->prepare("SELECT id, \"order\", toolType, toolLabel, prompt, originalPath, editedPath, createdAt
                                       FROM PhotoEdit
                                       WHERE photoProjectId = :projectId
                                       ORDER BY \"order\" ASC");
            $editStmt->execute([':projectId' => $project['id']]);
            $project['edits'] = $editStmt->fetchAll();
        }
        unset($project);

        echo json_encode($projects);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'خطأ في جلب المشاريع']);
    }
    exit;
}

if ($method === 'POST') {
    try {
        $input = json_decode(file_get_contents('php://input'), true);
        $title = $input['title'] ?? ('مشروع جديد — ' . date('Y-m-d H:i:s'));
        $status = $input['status'] ?? 'pending';

        $db = Database::getInstance();
        $id = 'proj-' . bin2hex(random_bytes(8));

        $stmt = $db->prepare("INSERT INTO PhotoProject (id, title, status, createdAt, updatedAt)
                              VALUES (:id, :title, :status, datetime('now'), datetime('now'))");
        $stmt->execute([
            ':id'     => $id,
            ':title'  => $title,
            ':status' => $status,
        ]);

        echo json_encode([
            'id'        => $id,
            'title'     => $title,
            'status'    => $status,
            'edits'     => [],
            'createdAt' => date('c'),
            'updatedAt' => date('c'),
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'خطأ في إنشاء المشروع']);
    }
    exit;
}

http_response_code(405);
echo json_encode(['error' => 'طريقة الطلب غير مدعومة']);