<?php
/**
 * SkyClaim — WPForms Webhook Receiver
 * 
 * Ezt a fájlt töltsd fel a cPanel szerveredre, pl:
 * https://eu261compensation.com/webhook.php
 * 
 * WPForms-ban állítsd be webhook URL-nek:
 * https://eu261compensation.com/webhook.php
 * 
 * A WPForms mezőneveket lent a FIELD MAPPING részben tudod módosítani.
 */

// ===== ADATBÁZIS BEÁLLÍTÁSOK — EZEKET ÍRD ÁT! =====
$DB_HOST = 'localhost';
$DB_NAME = 'deeldabr_eu261';
$DB_USER = 'deeldabr_eu261';
$DB_PASS = 'ASDjaS(DCWEFHjewke3we4f@#';

// ===== CORS & HEADERS =====
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    respond(405, 'Only POST requests accepted');
}

// ===== ADATOK FOGADÁSA =====
// WPForms JSON-t vagy form-data-t küldhet
$contentType = $_SERVER['CONTENT_TYPE'] ?? '';

if (strpos($contentType, 'application/json') !== false) {
    $input = json_decode(file_get_contents('php://input'), true) ?? [];
} else {
    $input = $_POST;
}

// ===== FIELD MAPPING =====
// Bal oldal: adatbázis oszlop neve
// Jobb oldal: a WPForms mező neve/ID-ja amit küld
// Ha más nevet küld a WPForms, csak itt írd át a jobb oldalt!

$booking_ref   = $input['booking_ref']   ?? $input['booking-ref']   ?? $input['field_1'] ?? '';
$flight_number = $input['flight_number'] ?? $input['flight-number'] ?? $input['field_2'] ?? '';
$flight_date   = $input['date']          ?? $input['flight_date']   ?? $input['field_3'] ?? '';
$reason        = $input['reason']        ?? $input['field_4']       ?? '';
$departure     = $input['departure']     ?? $input['field_5']       ?? '';
$arrival       = $input['arrival']       ?? $input['field_6']       ?? '';
$first_name    = $input['first_name']    ?? $input['first-name']    ?? $input['field_7'] ?? '';
$last_name     = $input['last_name']     ?? $input['last-name']     ?? $input['field_8'] ?? '';

// ===== VALIDÁCIÓ =====
if (empty($booking_ref) || empty($first_name) || empty($last_name)) {
    respond(400, 'Missing required fields: booking_ref, first_name, last_name');
}

// Dátum formázás (ha nem YYYY-MM-DD formátumban jön)
if (!empty($flight_date)) {
    $parsed = strtotime($flight_date);
    if ($parsed) {
        $flight_date = date('Y-m-d', $parsed);
    }
}

// ===== ADATBÁZIS KAPCSOLAT =====
try {
    $pdo = new PDO("mysql:host=$DB_HOST;dbname=$DB_NAME;charset=utf8mb4", $DB_USER, $DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
} catch (PDOException $e) {
    respond(500, 'Database connection failed');
}

// ===== CUSTOMER ID GENERÁLÁS =====
function generateCustomerId($booking, $first, $last) {
    $src = $first . $last . $booking . date('Ymd');
    $hash = strtoupper(substr(md5($src), 0, 8));
    return 'CU-' . $hash;
}

// ===== IS_MAIN: első utas ezzel a booking_ref-el =====
$stmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM customers WHERE booking_ref = ?");
$stmt->execute([$booking_ref]);
$existingCount = $stmt->fetch()['cnt'];
$is_main = ($existingCount == 0) ? 1 : 0;

// ===== CUSTOMER ID =====
$customer_id = generateCustomerId($booking_ref, $first_name, $last_name);

// Egyediség biztosítása
$stmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM customers WHERE customer_id = ?");
$stmt->execute([$customer_id]);
if ($stmt->fetch()['cnt'] > 0) {
    $customer_id = $customer_id . substr(uniqid(), -3);
}

// ===== BESZÚRÁS =====
try {
    $stmt = $pdo->prepare("
        INSERT INTO customers (customer_id, booking_ref, flight_number, flight_date, reason, departure, arrival, first_name, last_name, is_main, status)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'new')
    ");
    $stmt->execute([
        $customer_id,
        $booking_ref,
        $flight_number,
        $flight_date ?: null,
        $reason,
        $departure,
        $arrival,
        $first_name,
        $last_name,
        $is_main
    ]);

    $newId = $pdo->lastInsertId();

    respond(200, 'Customer saved successfully', [
        'id' => (int)$newId,
        'customer_id' => $customer_id,
        'is_main' => (bool)$is_main
    ]);

} catch (PDOException $e) {
    respond(500, 'Failed to save: ' . $e->getMessage());
}

// ===== HELPER =====
function respond($code, $message, $data = []) {
    http_response_code($code);
    echo json_encode(array_merge(['status' => $code, 'message' => $message], $data));
    exit;
}
