<?php
declare(strict_types=1);
require __DIR__ . '/bootstrap.php';

$user = require_user();
$course = active_course();
ensure_enrollment((int) $user['id'], (int) $course['id']);

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
    $classStmt = db()->prepare(
        'SELECT cc.class_slug
         FROM class_progress cp
         JOIN course_classes cc ON cc.id = cp.course_class_id
         WHERE cp.user_id = :user_id AND cc.course_id = :course_id'
    );
    $classStmt->execute([
        'user_id' => $user['id'],
        'course_id' => $course['id'],
    ]);

    $projectStmt = db()->prepare(
        'SELECT item_key, is_completed
         FROM project_progress
         WHERE user_id = :user_id AND course_id = :course_id'
    );
    $projectStmt->execute([
        'user_id' => $user['id'],
        'course_id' => $course['id'],
    ]);

    json_response([
        'completed_class_ids' => array_column($classStmt->fetchAll(), 'class_slug'),
        'project_checks' => array_reduce(
            $projectStmt->fetchAll(),
            function (array $carry, array $item): array {
                $carry[$item['item_key']] = (bool) $item['is_completed'];
                return $carry;
            },
            []
        ),
        'certificate_status' => certificate_status((int) $user['id'], (int) $course['id']),
    ]);
}

require_method('POST');
$data = read_json();
$action = (string) ($data['action'] ?? '');

if ($action === 'complete_class') {
    $classSlug = (string) ($data['class_id'] ?? '');
    $classStmt = db()->prepare(
        'SELECT id
         FROM course_classes
         WHERE course_id = :course_id AND class_slug = :class_slug
         LIMIT 1'
    );
    $classStmt->execute([
        'course_id' => $course['id'],
        'class_slug' => $classSlug,
    ]);
    $class = $classStmt->fetch();
    if (!$class) {
        json_response(['error' => 'Class not found.'], 404);
    }

    $stmt = db()->prepare(
        'INSERT OR IGNORE INTO class_progress (user_id, course_class_id)
         VALUES (:user_id, :course_class_id)'
    );
    $stmt->execute([
        'user_id' => $user['id'],
        'course_class_id' => $class['id'],
    ]);

    json_response([
        'ok' => true,
        'certificate_status' => certificate_status((int) $user['id'], (int) $course['id']),
    ]);
}

if ($action === 'toggle_project_item') {
    $itemKey = trim((string) ($data['item_key'] ?? ''));
    $isCompleted = !empty($data['is_completed']) ? 1 : 0;

    if ($itemKey === '') {
        json_response(['error' => 'Project item is required.'], 422);
    }

    $stmt = db()->prepare(
        'INSERT INTO project_progress (user_id, course_id, item_key, is_completed)
         VALUES (:user_id, :course_id, :item_key, :is_completed)
         ON CONFLICT(user_id, course_id, item_key)
         DO UPDATE SET
           is_completed = excluded.is_completed,
           updated_at = CURRENT_TIMESTAMP'
    );
    $stmt->execute([
        'user_id' => $user['id'],
        'course_id' => $course['id'],
        'item_key' => $itemKey,
        'is_completed' => $isCompleted,
    ]);

    json_response(['ok' => true]);
}

json_response(['error' => 'Unsupported progress action.'], 422);
