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

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

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

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    if (!$conn) {
        throw new Exception("Keine Datenbankverbindung möglich");
    }
    
    // Get appointment ID from request
    $appointmentId = $_GET['appointmentId'] ?? $_POST['appointmentId'] ?? null;
    
    if (!$appointmentId) {
        throw new Exception('Termin-ID ist erforderlich');
    }
    
    // Get all offer tracking records for this appointment
    $stmt = $conn->prepare("
        SELECT 
            ot.*,
            a.customer_name,
            a.license_plate,
            a.phone,
            a.email as customer_email,
            CASE 
                WHEN ot.offer_type = 'sent' AND EXISTS (
                    SELECT 1 FROM customer_selections cs 
                    WHERE cs.appointment_id = ot.appointment_id 
                    AND (cs.tire_selection != '[]' OR cs.service_selection != '[]' OR cs.customer_notes != '')
                ) THEN 1
                ELSE 0
            END as customer_accepted
        FROM offer_tracking ot
        LEFT JOIN appointments a ON ot.appointment_id = a.id
        WHERE ot.appointment_id = ?
        ORDER BY ot.created_at DESC
    ");
    
    $stmt->execute([$appointmentId]);
    $offers = $stmt->fetchAll();
    
    // Process offer data
    foreach ($offers as &$offer) {
        $offer['offer_data'] = json_decode($offer['offer_data'], true);
        $offer['created_at_formatted'] = date('d.m.Y H:i', strtotime($offer['created_at']));
    }
    
    echo json_encode([
        'success' => true,
        'offers' => $offers
    ]);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>
