<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

session_start();
$pdo = require_once __DIR__ . '/../../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$id = basename($path);

function response($data, $status = 200) {
    http_response_code($status);
    echo json_encode($data);
    exit;
}

function getJsonInput() {
    return json_decode(file_get_contents('php://input'), true);
}

function checkAuth() {
    if (empty($_SESSION['user_id'])) {
        response(['error' => 'Unauthorized'], 401);
    }
    return $_SESSION['user_id'];
}

// Get schedules
if ($method === 'GET') {
    $userId = checkAuth();
    
    $dateFrom = $_GET['from'] ?? date('Y-m-d', strtotime('-30 days'));
    $dateTo = $_GET['to'] ?? date('Y-m-d', strtotime('+30 days'));
    
    $stmt = $pdo->prepare('
        SELECT id, title, subject, start_time, end_time, type, ai_generated, color, memo
        FROM schedules
        WHERE user_id = ? AND DATE(start_time) BETWEEN ? AND ?
        ORDER BY start_time ASC
    ');
    $stmt->execute([$userId, $dateFrom, $dateTo]);
    $schedules = $stmt->fetchAll();
    
    response(['schedules' => $schedules]);
}

// Create schedule
elseif ($method === 'POST') {
    $userId = checkAuth();
    $data = getJsonInput();
    
    if (empty($data['title']) || empty($data['start_time']) || empty($data['end_time'])) {
        response(['error' => 'Missing required fields'], 400);
    }
    
    $stmt = $pdo->prepare('
        INSERT INTO schedules (user_id, title, subject, start_time, end_time, type, color, memo, ai_generated)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ');
    
    $stmt->execute([
        $userId,
        $data['title'],
        $data['subject'] ?? null,
        $data['start_time'],
        $data['end_time'],
        $data['type'] ?? 'schedule',
        $data['color'] ?? '#3B82F6',
        $data['memo'] ?? '',
        $data['ai_generated'] ?? false
    ]);
    
    response([
        'success' => true,
        'id' => $pdo->lastInsertId(),
        'message' => 'Schedule created'
    ], 201);
}

// Update schedule
elseif ($method === 'PUT') {
    $userId = checkAuth();
    $scheduleId = (int)$id;
    $data = getJsonInput();
    
    // Verify ownership
    $stmt = $pdo->prepare('SELECT user_id FROM schedules WHERE id = ?');
    $stmt->execute([$scheduleId]);
    $schedule = $stmt->fetch();
    
    if (!$schedule || $schedule['user_id'] !== $userId) {
        response(['error' => 'Unauthorized'], 403);
    }
    
    $stmt = $pdo->prepare('
        UPDATE schedules
        SET title = ?, subject = ?, start_time = ?, end_time = ?, type = ?, color = ?, memo = ?
        WHERE id = ?
    ');
    
    $stmt->execute([
        $data['title'] ?? $schedule['title'],
        $data['subject'] ?? null,
        $data['start_time'] ?? $schedule['start_time'],
        $data['end_time'] ?? $schedule['end_time'],
        $data['type'] ?? 'schedule',
        $data['color'] ?? '#3B82F6',
        $data['memo'] ?? '',
        $scheduleId
    ]);
    
    response(['success' => true, 'message' => 'Schedule updated']);
}

// Delete schedule
elseif ($method === 'DELETE') {
    $userId = checkAuth();
    $scheduleId = (int)$id;
    
    $stmt = $pdo->prepare('SELECT user_id FROM schedules WHERE id = ?');
    $stmt->execute([$scheduleId]);
    $schedule = $stmt->fetch();
    
    if (!$schedule || $schedule['user_id'] !== $userId) {
        response(['error' => 'Unauthorized'], 403);
    }
    
    $stmt = $pdo->prepare('DELETE FROM schedules WHERE id = ?');
    $stmt->execute([$scheduleId]);
    
    response(['success' => true, 'message' => 'Schedule deleted']);
}

else {
    response(['error' => 'Method not allowed'], 405);
}
?>
