<?php
/**
 * Appointments API - Vereinfachte Version ohne E-Mail/API-Features
 */

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

require_once __DIR__ . '/../config/database.php';

$method = $_SERVER['REQUEST_METHOD'];
$db = new Database();
$conn = $db->getConnection();

/**
 * Prüft Reifenstatus für einen Termin - DEAKTIVIERT
 * Die check_tire_status.php API existiert nicht mehr
 */
function checkTireStatusForAppointment($autohausId, $einlagerungsnummer) {
    // Reifenstatus-Prüfung wurde deaktiviert
    return null;
}

try {
    switch ($method) {
        case 'GET':
            handleGetRequest($conn);
            break;
        case 'POST':
            handlePostRequest($conn);
            break;
        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'error' => 'Method not allowed']);
            break;
    }
} catch (Exception $e) {
    error_log("General error in appointments.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

function handleGetRequest($conn) {
    $event_id = $_GET['event_id'] ?? null;
    $date = $_GET['date'] ?? null;
    
    if (!$event_id || !$date) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Event ID and date are required']);
        return;
    }
    
    // Get available time slots for the event and date
    $stmt = $conn->prepare("
        SELECT 
            e.id as event_id,
            e.name as event_name,
            e.event_date,
            e.start_time,
            e.end_time,
            e.slot_duration,
            e.max_monteure,
            e.pause_start,
            e.pause_end,
            e.blocked_start,
            e.blocked_end
        FROM events e 
        WHERE e.id = ? AND e.is_active = 1
    ");
    $stmt->execute([$event_id]);
    $event = $stmt->fetch();
    
    if (!$event) {
        echo json_encode(['success' => false, 'error' => 'Event nicht gefunden']);
        return;
    }
    
    // Get booked appointments for the date (including all active statuses)
    $stmt = $conn->prepare("
        SELECT slot_time, COUNT(*) as booked_count
        FROM appointments 
        WHERE event_id = ? AND slot_date = ? AND status IN ('pending', 'approved', 'booked', 'vorbereitet', 'completed')
        GROUP BY slot_time
    ");
    $stmt->execute([$event_id, $date]);
    $bookedSlots = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
    
    
    // Generate available time slots
    $availableSlots = generateTimeSlots($event, $bookedSlots);
    
    echo json_encode([
        'success' => true,
        'event' => $event,
        'available_slots' => $availableSlots,
        'date' => $date
    ]);
}

function handlePostRequest($conn) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    
    if (!$input) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Invalid JSON data']);
        return;
    }
    
    // Validate required fields
    $required_fields = ['event_id', 'customer_name', 'license_plate', 'phone', 'email', 'slot_time', 'slot_date'];
    foreach ($required_fields as $field) {
        if (empty($input[$field])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => "Field '$field' is required"]);
            return;
        }
    }
    
    try {
        // Insert appointment as directly booked
        // Get autohaus_id from event
        $stmt = $conn->prepare("SELECT autohaus_id FROM events WHERE id = ?");
        $stmt->execute([$input['event_id']]);
        $event = $stmt->fetch();
        $autohaus_id = $event['autohaus_id'] ?? $input['autohaus_id'] ?? null;
        
        // Reifenstatus-Prüfung wurde deaktiviert
        $tireStatus = null;
        $tireRecommendation = null;
        
        $stmt = $conn->prepare("
            INSERT INTO appointments (
                event_id, autohaus_id, customer_name, license_plate, phone, email, slot_time, slot_date,
                storage_number, brings_wheels, wheels_storage_action, seasonal_check,
                info_text, has_wheel_lock, status, source
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'booked', 'website')
        ");
        
        $stmt->execute([
            $input['event_id'],
            $autohaus_id,
            $input['customer_name'],
            $input['license_plate'],
            $input['phone'],
            $input['email'],
            $input['slot_time'],
            $input['slot_date'],
            $input['storage_number'] ?? null,
            $input['brings_wheels'] ?? true,
            $input['wheels_storage_action'] ?? 'store',
            $input['seasonal_check'] ?? 'none',
            $input['info_text'] ?? null,
            $input['has_wheel_lock'] ?? false
        ]);
        
        $appointment_id = $conn->lastInsertId();
        
        echo json_encode([
            'success' => true,
            'message' => 'Termin erfolgreich gebucht',
            'appointment_id' => $appointment_id
        ]);
        
    } catch (Exception $e) {
        error_log("Database error in appointments.php: " . $e->getMessage());
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Fehler beim Speichern des Termins: ' . $e->getMessage()]);
    }
}

function generateTimeSlots($event, $bookedSlots) {
    $slots = [];
    $start_time = new DateTime($event['start_time']);
    $end_time = new DateTime($event['end_time']);
    $slot_duration = $event['slot_duration'];
    $max_monteure = $event['max_monteure'];
    
    // Parse pause times if they exist
    $pause_start = $event['pause_start'] ? new DateTime($event['pause_start']) : null;
    $pause_end = $event['pause_end'] ? new DateTime($event['pause_end']) : null;
    $blocked_start = $event['blocked_start'] ? new DateTime($event['blocked_start']) : null;
    $blocked_end = $event['blocked_end'] ? new DateTime($event['blocked_end']) : null;
    
    $current_time = clone $start_time;
    
    while ($current_time < $end_time) {
        $time_str = $current_time->format('H:i');
        $time_str_with_seconds = $current_time->format('H:i:s');
        
        // Check if this time is in pause or blocked period
        $is_paused = false;
        $is_blocked = false;
        
        if ($pause_start && $pause_end && $current_time >= $pause_start && $current_time < $pause_end) {
            $is_paused = true;
        }
        
        if ($blocked_start && $blocked_end && $current_time >= $blocked_start && $current_time < $blocked_end) {
            $is_blocked = true;
        }
        
        if (!$is_paused && !$is_blocked) {
            // Try both formats for backward compatibility
            $booked_count = $bookedSlots[$time_str] ?? $bookedSlots[$time_str_with_seconds] ?? 0;
            $available_count = $max_monteure - $booked_count;
            $is_available = $available_count > 0;
            
            $slots[] = [
                'time' => $time_str,
                'formatted_time' => $time_str,
                'available' => $is_available,
                'available_count' => $available_count,
                'booked' => $booked_count,
                'max' => $max_monteure,
                'max_count' => $max_monteure,
                'is_available' => $is_available
            ];
        }
        
        $current_time->add(new DateInterval('PT' . $slot_duration . 'M'));
    }
    
    return $slots;
}
?>
