<?php
/**
 * Folders API for door configurations.
 *
 * GET  ?email=xxx  – list folders for that customer (for storefront dropdown).
 * POST – create folder. Body: { "name": "Folder name", "customer_email": "user@example.com" }
 */
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: https://shopify.vintagedoors.com');
header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

require __DIR__ . '/../admin/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $email = trim($_GET['email'] ?? '');
    if (!$email) {
        http_response_code(400);
        echo json_encode(['error' => 'email is required']);
        exit;
    }
    $stmt = $pdo->prepare('SELECT id, name, customer_email, created_at FROM door_folders WHERE customer_email = ? ORDER BY name ASC');
    $stmt->execute([$email]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $list = [];
    foreach ($rows as $r) {
        $list[] = [
            'id'             => (int) $r['id'],
            'name'           => $r['name'],
            'customer_email' => $r['customer_email'],
            'created_at'     => $r['created_at'],
        ];
    }
    echo json_encode($list);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
$name = isset($data['name']) ? trim((string) $data['name']) : '';
$customer_email = isset($data['customer_email']) ? trim((string) $data['customer_email']) : '';

if ($name === '') {
    http_response_code(400);
    echo json_encode(['error' => 'name is required']);
    exit;
}

$stmt = $pdo->prepare('INSERT INTO door_folders (name, customer_email) VALUES (?, ?)');
$stmt->execute([$name, $customer_email ?: null]);
$id = (int) $pdo->lastInsertId();
echo json_encode(['id' => $id, 'name' => $name, 'customer_email' => $customer_email ?: null]);
exit;
