<?php

declare(strict_types=1);

/**
 * api.fahrschultermin.de — Full API entry point
 * Handles all /api/v1/* routes + CORS + Session auth
 */

const BASE_PATH = __DIR__ . '/..';

spl_autoload_register(static function (string $class): void {
    $prefix = 'App\\';

    if (!str_starts_with($class, $prefix)) {
        return;
    }

    $relativeClass = substr($class, strlen($prefix));
    $path = BASE_PATH . '/app/' . str_replace('\\', '/', $relativeClass) . '.php';

    if (is_file($path)) {
        require_once $path;
    }
});

$config = require BASE_PATH . '/config/app.php';

date_default_timezone_set('UTC');
session_name($config['session_name']);

// ── CORS ──────────────────────────────────────────────────────────────────────
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
$allowed = $config['cors_allowed_origins'] ?? [];
$isAllowed = in_array($origin, $allowed, true);

header('Access-Control-Allow-Origin: ' . ($isAllowed ? $origin : ''), true);
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Max-Age: 86400');

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

// ── Session ───────────────────────────────────────────────────────────────────
$sessionPath = $config['session_path'] ?? BASE_PATH . '/storage/sessions';
if (!is_dir($sessionPath)) {
    mkdir($sessionPath, 0775, true);
}

session_save_path($sessionPath);

$isHttps = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
$sameSite = $isHttps ? 'None' : 'Lax';

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'domain' => $config['session_domain'] ?? '',
    'secure' => $isHttps,
    'httponly' => true,
    'samesite' => $sameSite,
]);

session_start();

// ── Database ───────────────────────────────────────────────────────────────────
\App\Support\Database::configure($config);

// ── Router ─────────────────────────────────────────────────────────────────────
use App\Http\Controllers\AppointmentsController;
use App\Http\Controllers\AuthController;
use App\Http\Controllers\BootstrapController;
use App\Http\Controllers\InstructorsController;
use App\Http\Controllers\ReferenceDataController;
use App\Http\Controllers\StudentsController;
use App\Http\Controllers\TenantsController;
use App\Http\Controllers\UsersController;
use App\Http\Controllers\WorkTimesheetController;
use App\Http\Controllers\StudentAuthController;
use App\Http\Controllers\StudentController;
use App\Http\Controllers\InstructorController;
use App\Http\Controllers\TenantController;
use App\Support\Request;
use App\Support\Router;

$request = new Request();
$router = new Router($request);
$path = $request->path();

// ── API Routes ─────────────────────────────────────────────────────────────────
if (str_starts_with($path, '/api/v1')) {
    $auth = new AuthController();
    $bootstrapController = new BootstrapController();
    $students = new StudentsController();
    $references = new ReferenceDataController();
    $appointments = new AppointmentsController();
    $users = new UsersController();
    $tenants = new TenantsController();
    $instructors = new InstructorsController();
    $workTimesheet = new WorkTimesheetController();
    $studentAuth = new StudentAuthController();
    $student = new StudentController();
    $instructorCtrl = new InstructorController();
    $tenantCtrl = new TenantController();

    // ── Auth (bestehend) ──────────────────────────────────────────────────────
    $router->post('/api/v1/auth/login', [$auth, 'login']);
    $router->post('/api/v1/auth/logout', [$auth, 'logout']);
    $router->get('/api/v1/auth/me', [$auth, 'me']);

    // ── Student Auth (neu) ──────────────────────────────────────────────────────
    $router->post('/api/v1/auth/register-student', [$studentAuth, 'register']);

    // ── Student me ─────────────────────────────────────────────────────────────
    $router->get('/api/v1/student/me', [$studentAuth, 'me']);

    // ── Bootstrap + Reference ──────────────────────────────────────────────────
    $router->get('/api/v1/bootstrap', $bootstrapController);
    $router->get('/api/v1/students', [$students, 'index']);
    $router->post('/api/v1/students', [$students, 'store']);
    $router->patch('/api/v1/students/{id}/training', [$students, 'updateTraining']);
    $router->patch('/api/v1/students/{id}', [$students, 'update']);
    $router->delete('/api/v1/students/{id}', [$students, 'destroy']);
    $router->get('/api/v1/lesson-types', [$references, 'lessonTypes']);
    $router->post('/api/v1/lesson-types', [$references, 'storeLessonType']);
    $router->post('/api/v1/lesson-types/reorder', [$references, 'reorderLessonTypes']);
    $router->patch('/api/v1/lesson-types/{id}', [$references, 'updateLessonType']);
    $router->delete('/api/v1/lesson-types/{id}', [$references, 'destroyLessonType']);
    $router->post('/api/v1/lesson-types/visibility', [$references, 'updateLessonTypeMatrix']);
    $router->get('/api/v1/license-class-templates', [$references, 'templates']);
    $router->post('/api/v1/license-class-templates', [$references, 'storeTemplate']);
    $router->patch('/api/v1/license-class-templates/{id}', [$references, 'updateTemplate']);

    // ── Instructors ────────────────────────────────────────────────────────────
    $router->get('/api/v1/instructors', [$instructors, 'index']);
    $router->post('/api/v1/instructors', [$instructors, 'store']);
    $router->patch('/api/v1/instructors/{id}', [$instructors, 'update']);

    // ── Instructor Settings (neu) ───────────────────────────────────────────────
    $router->get('/api/v1/instructors/{id}/availability', [$instructorCtrl, 'availability']);
    $router->put('/api/v1/instructors/{id}/availability', [$instructorCtrl, 'availabilityUpdate']);
    $router->get('/api/v1/instructors/{id}/booking-settings', [$instructorCtrl, 'bookingSettings']);
    $router->patch('/api/v1/instructors/{id}/booking-settings', [$instructorCtrl, 'bookingSettingsUpdate']);

    // ── Instructor Vacations ───────────────────────────────────────────────────
    $router->get('/api/v1/instructors/{id}/vacations', [$instructorCtrl, 'vacations']);
    $router->post('/api/v1/instructors/{id}/vacations', [$instructorCtrl, 'vacationsCreate']);
    $router->delete('/api/v1/instructors/{id}/vacations/{vacation_id}', [$instructorCtrl, 'vacationsDelete']);

    // ── Instructor Private Appointments ────────────────────────────────────────
    $router->get('/api/v1/instructors/{id}/private-appointments', [$instructorCtrl, 'privateAppointments']);
    $router->post('/api/v1/instructors/{id}/private-appointments', [$instructorCtrl, 'privateAppointmentsCreate']);
    $router->delete('/api/v1/instructors/{id}/private-appointments/{priv_id}', [$instructorCtrl, 'privateAppointmentsDelete']);

    // ── Instructor Multi-Tenant ─────────────────────────────────────────────────
    $router->get('/api/v1/instructors/{id}/tenants', [$instructorCtrl, 'tenants']);
    $router->post('/api/v1/instructors/{id}/tenants', [$instructorCtrl, 'tenantsAdd']);
    $router->delete('/api/v1/instructors/{id}/tenants/{tenant_id}', [$instructorCtrl, 'tenantsRemove']);
    $router->get('/api/v1/instructors/{id}/travel-times', [$instructorCtrl, 'travelTimes']);
    $router->post('/api/v1/instructors/{id}/travel-times', [$instructorCtrl, 'travelTimesUpsert']);
    $router->delete('/api/v1/instructors/{id}/travel-times/{tt_id}', [$instructorCtrl, 'travelTimesDelete']);
    $router->get('/api/v1/instructors/{id}/home-to-tenant', [$instructorCtrl, 'homeToTenant']);
    $router->post('/api/v1/instructors/{id}/home-to-tenant', [$instructorCtrl, 'homeToTenantUpsert']);
    $router->delete('/api/v1/instructors/{id}/home-to-tenant/{ht_id}', [$instructorCtrl, 'homeToTenantDelete']);

    // ── Instructor Break Rules ─────────────────────────────────────────────────
    $router->get('/api/v1/instructors/{id}/break-rules', [$instructorCtrl, 'breakRules']);
    $router->post('/api/v1/instructors/{id}/break-rules', [$instructorCtrl, 'breakRulesCreate']);
    $router->put('/api/v1/instructors/{id}/break-rules/{rule_id}', [$instructorCtrl, 'breakRulesUpdate']);
    $router->patch('/api/v1/instructors/{id}/break-rules/{rule_id}/toggle', [$instructorCtrl, 'breakRulesToggle']);
    $router->delete('/api/v1/instructors/{id}/break-rules/{rule_id}', [$instructorCtrl, 'breakRulesDelete']);

    // ── Instructor Appointment Requests ─────────────────────────────────────────
    $router->get('/api/v1/instructor/appointment-requests', [$instructorCtrl, 'appointmentRequests']);
    $router->patch('/api/v1/instructor/appointment-requests/{id}/respond', [$instructorCtrl, 'appointmentRequestsRespond']);

    // ── Users ───────────────────────────────────────────────────────────────────
    $router->get('/api/v1/users', [$users, 'index']);
    $router->post('/api/v1/users', [$users, 'store']);
    $router->patch('/api/v1/users/{id}', [$users, 'update']);

    // ── Tenants ────────────────────────────────────────────────────────────────
    $router->get('/api/v1/tenants', [$tenants, 'index']);
    $router->post('/api/v1/tenants', [$tenants, 'store']);
    $router->patch('/api/v1/tenants/{id}', [$tenants, 'update']);
    $router->patch('/api/v1/tenant/profile', [$tenants, 'updateOwn']);

    // ── Tenant Admin (neu) ─────────────────────────────────────────────────────
    $router->get('/api/v1/tenant/pending-registrations', [$tenantCtrl, 'pendingRegistrations']);
    $router->patch('/api/v1/tenant/student-tenants/{id}/confirm', [$tenantCtrl, 'confirmStudentTenant']);
    $router->get('/api/v1/tenant/registration-code', [$tenantCtrl, 'getRegistrationCode']);
    $router->put('/api/v1/tenant/registration-code', [$tenantCtrl, 'updateRegistrationCode']);
    $router->patch('/api/v1/tenant/cancellation-settings', [$tenantCtrl, 'cancellationSettings']);

    // ── Student Portal (neu) ──────────────────────────────────────────────────
    $router->get('/api/v1/student/instructors', [$student, 'instructors']);
    $router->get('/api/v1/student/instructors/{id}/slots', [$student, 'instructorSlots']);
    $router->post('/api/v1/student/appointment-requests', [$student, 'createAppointmentRequest']);
    $router->get('/api/v1/student/appointment-requests', [$student, 'appointmentRequests']);
    $router->post('/api/v1/student/add-tenant', [$student, 'addTenant']);

    // ── Appointments ──────────────────────────────────────────────────────────
    $router->get('/api/v1/appointments', [$appointments, 'index']);
    $router->post('/api/v1/appointments/validate', [$appointments, 'validate']);
    $router->post('/api/v1/appointments', [$appointments, 'store']);
    $router->patch('/api/v1/appointments/{id}', [$appointments, 'update']);
    $router->delete('/api/v1/appointments/{id}', [$appointments, 'destroy']);

    // ── Reports ───────────────────────────────────────────────────────────────
    $router->get('/api/v1/reports/work-timesheet', [$workTimesheet, 'index']);

    $router->dispatch();
    exit;
}

// ── 404 ────────────────────────────────────────────────────────────────────────
http_response_code(404);
header('Content-Type: application/json');
echo json_encode(['message' => 'Not Found']);