<?php
// ============================================================
// Design2Clothes — Projects API
// Simple CRUD simulation for projects.
// (In a real scenario, this would interface with a DB)
// ============================================================
session_name('d2c_session');
session_start();
require_once __DIR__ . '/../config.php';

d2c_cors_headers();

$projectsFile = UPLOAD_DIR . 'projects.json';

// Helper to read JSON
function get_projects() {
    global $projectsFile;
    if (!file_exists($projectsFile)) return [];
    return json_decode(file_get_contents($projectsFile), true) ?: [];
}

// Helper to write JSON
function save_projects($data) {
    global $projectsFile;
    file_put_contents($projectsFile, json_encode($data, JSON_PRETTY_PRINT));
}

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        $projects = get_projects();
        // If empty, return a fake demo project just to show UI
        if (empty($projects)) {
             $projects = [
                 ['id' => 'p_1', 'title' => 'ThreadVision FW24 Capsule', 'created' => date('Y-m-d H:i', strtotime('-2 days'))],
                 ['id' => 'p_2', 'title' => 'Neon Streetwear Concept', 'created' => date('Y-m-d H:i', strtotime('-1 days'))]
             ];
             save_projects($projects);
        }
        d2c_json(['success' => true, 'projects' => $projects]);
        break;

    case 'POST':
        // Future implementation: create project logic
        d2c_json(['success' => true, 'message' => 'Project created']);
        break;

    default:
        d2c_error('Method not allowed', 405);
}
