<?php
/**
 * Single Project API Endpoint
 * GET: Get single project with edits (query param: ?id=xxx)
 * DELETE: Delete project and its files (query param: ?id=xxx)
 */

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

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

$method = $_SERVER['REQUEST_METHOD'];
$id = $_GET['id'] ?? '';

if (empty($id)) {
    http_response_code(400);
    echo json_encode(['error' => 'معرف المشروع مطلوب']);
    exit;
}

$baseDir = dirname(__DIR__);

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

        $stmt = $db->prepare("SELECT * FROM PhotoProject WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $project = $stmt->fetch();

        if (!$project) {
            http_response_code(404);
            echo json_encode(['error' => 'المشروع غير موجود']);
            exit;
        }

        // Get edits
        $editStmt = $db->prepare("SELECT * FROM PhotoEdit
                                   WHERE photoProjectId = :projectId
                                   ORDER BY \"order\" ASC");
        $editStmt->execute([':projectId' => $id]);
        $project['edits'] = $editStmt->fetchAll();

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

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

        // Get project with edits
        $stmt = $db->prepare("SELECT * FROM PhotoProject WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $project = $stmt->fetch();

        if (!$project) {
            http_response_code(404);
            echo json_encode(['error' => 'المشروع غير موجود']);
            exit;
        }

        // Get edits to delete associated files
        $editStmt = $db->prepare("SELECT editedPath FROM PhotoEdit WHERE photoProjectId = :projectId");
        $editStmt->execute([':projectId' => $id]);
        $edits = $editStmt->fetchAll();

        // Delete edited image files
        foreach ($edits as $edit) {
            if (!empty($edit['editedPath'])) {
                $filepath = $baseDir . '/public' . $edit['editedPath'];
                if (file_exists($filepath)) {
                    @unlink($filepath);
                }
            }
        }

        // Delete edits (cascade should handle this with PRAGMA foreign_keys=ON, but be explicit)
        $db->prepare("DELETE FROM PhotoEdit WHERE photoProjectId = :projectId")
           ->execute([':projectId' => $id]);

        // Delete the project
        $db->prepare("DELETE FROM PhotoProject WHERE id = :id")
           ->execute([':id' => $id]);

        echo json_encode(['success' => true]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'خطأ في حذف المشروع']);
    }
    exit;
}

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