<?php
// ── Chupito Terminál — centrálny login endpoint ────────────────────────────
// POST JSON: { email, password }
// Odpoveď:   { success, token, restaurant, restaurant_name, api_url, user, fcm_topic }
// Pri viacerých reštauráciách: { success, multiple: true, options: [...] }
// POST JSON s výberom: { email, password, slug }

date_default_timezone_set('Europe/Bratislava');
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: POST, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

// SaaS DB — centrálna evidencia reštaurácií
$SAAS_DB_HOST = 'localhost';
$SAAS_DB_NAME = 'chupito_saas';
$SAAS_DB_USER = 'chupito_saas';
$SAAS_DB_PASS = 'SaaS2026x!';

$input = json_decode(file_get_contents('php://input'), true);
$email = trim($input['email'] ?? '');
$password = $input['password'] ?? '';
$selectedSlug = trim($input['slug'] ?? '');

if (!$email || !$password) {
    echo json_encode(['success' => false, 'error' => 'Chýba e-mail alebo heslo.']);
    exit;
}

try {
    $saas = new PDO(
        "mysql:host=$SAAS_DB_HOST;dbname=$SAAS_DB_NAME;charset=utf8mb4",
        $SAAS_DB_USER, $SAAS_DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Chyba servera.']);
    exit;
}

// Aktívne reštaurácie (vrátane per-inštancia DB credentials)
$stmt = $saas->query("SELECT slug, restaurant_name, subdomain, db_name, db_user, db_pass FROM customers WHERE status = 'active'");
$restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Doplniť manuálne provisionované inštancie, ktoré nie sú v customers
// (PH a MP boli vytvorené pred SaaS pipeline)
$legacy = [
    ['slug' => 'plzenska', 'restaurant_name' => 'Plzeňská Hodovňa', 'subdomain' => 'reserve.chupito.sk', 'db_name' => 'chupito_reserve', 'db_user' => 'chupito_reserve', 'db_pass' => 'Reserve2026x'],
    ['slug' => 'malacka', 'restaurant_name' => 'Malacká Plzeňka', 'subdomain' => 'malackaplzenka.reserve.chupito.sk', 'db_name' => 'mp_reserve', 'db_user' => 'mp_reserve', 'db_pass' => 'MPReserve2026x'],
];
$known = array_column($restaurants, 'slug');
foreach ($legacy as $l) {
    if (!in_array($l['slug'], $known)) $restaurants[] = $l;
}

// Hľadaj usera vo všetkých inštanciách
$matches = [];
foreach ($restaurants as $r) {
    try {
        $db = new PDO(
            "mysql:host=localhost;dbname={$r['db_name']};charset=utf8mb4",
            $r['db_user'], $r['db_pass'],
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
        );
        $u = $db->prepare("SELECT id, name, email, password_hash, role FROM users WHERE email = ?");
        $u->execute([$email]);
        $user = $u->fetch(PDO::FETCH_ASSOC);
        if ($user && password_verify($password, $user['password_hash'])) {
            $matches[] = ['restaurant' => $r, 'user' => $user];
        }
    } catch (Exception $e) {
        continue; // inštancia nedostupná — preskočiť
    }
}

if (count($matches) === 0) {
    echo json_encode(['success' => false, 'error' => 'Nesprávne prihlasovacie údaje.']);
    exit;
}

// Viac reštaurácií a nie je vybraná -> ponúknuť výber
if (count($matches) > 1 && !$selectedSlug) {
    echo json_encode([
        'success' => true,
        'multiple' => true,
        'options' => array_map(fn($m) => [
            'slug' => $m['restaurant']['slug'],
            'name' => $m['restaurant']['restaurant_name'],
        ], $matches),
    ]);
    exit;
}

// Vybrať match
$chosen = $matches[0];
if ($selectedSlug) {
    foreach ($matches as $m) {
        if ($m['restaurant']['slug'] === $selectedSlug) { $chosen = $m; break; }
    }
}

$r = $chosen['restaurant'];
$user = $chosen['user'];

// Jednoduchý token: HMAC z user id + slug + deň (stačí pre appku; JWT môžeme neskôr)
$SECRET = 'chupito-terminal-secret-2026'; // TODO: presunúť do konfigurácie
$token = hash_hmac('sha256', $user['id'] . '|' . $r['slug'] . '|' . date('Y-m-d'), $SECRET);

echo json_encode([
    'success' => true,
    'token' => $token,
    'restaurant' => $r['slug'],
    'restaurant_name' => $r['restaurant_name'],
    'api_url' => 'https://' . $r['subdomain'] . '/api.php',
    'user' => ['id' => (int)$user['id'], 'name' => $user['name'], 'role' => $user['role']],
    'fcm_topic' => 'restaurant_' . $r['slug'],
]);
