<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['POST']);
header('Content-Type: application/json');

// Get authenticated user
$authUser = hw_get_auth_user();
if (!$authUser) {
    hw_json(['message' => 'Please log in to book appointments'], 401);
}
$userId = $authUser['id'];

$input = hw_input_json();
$coachId = $input['coach_id'] ?? null;
$startsAt = $input['starts_at'] ?? null;
$endsAt = $input['ends_at'] ?? null;
$notes = $input['notes'] ?? '';

if (!$coachId || !$startsAt || !$endsAt) {
    hw_json(['message' => 'Missing required fields'], 400);
}

try {
    $pdo = hw_db();
    
    // Insert appointment into database
    $stmt = $pdo->prepare('
        INSERT INTO appointments (user_id, coach_id, starts_at, ends_at, status, notes, created_at) 
        VALUES (?, ?, ?, ?, "scheduled", ?, NOW())
    ');
    
    $stmt->execute([
        $userId,
        $coachId, 
        $startsAt,
        $endsAt,
        $notes
    ]);
    
    $appointmentId = $pdo->lastInsertId();
    
    // Log the appointment creation
    $auditStmt = $pdo->prepare('
        INSERT INTO audit_logs (user_id, action, meta) 
        VALUES (?, "appointment_created", JSON_OBJECT("appointment_id", ?, "coach_id", ?))
    ');
    $auditStmt->execute([$userId, $appointmentId, $coachId]);
    
    hw_json([
        'success' => true,
        'message' => 'Appointment created successfully',
        'appointment_id' => $appointmentId,
        'starts_at' => $startsAt,
        'ends_at' => $endsAt
    ]);
    
} catch (Exception $e) {
    error_log('Appointment creation error: ' . $e->getMessage());
    hw_json(['message' => 'Failed to create appointment: ' . $e->getMessage()], 500);
}
?>