<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => false, 'public' => true]);
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE

// Start session AFTER config (so cookie params are correct)
if (function_exists('start_secure_session')) {
    start_secure_session();
} elseif (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    Kernel::fail('method_not_allowed', '', 405);
}

// قراءة البيانات قبل بدء الـ session
$b     = json_decode(file_get_contents('php://input'), true) ?? [];
$email = trim(strtolower($b['email'] ?? ''));
$pass  = $b['password'] ?? '';

if (!$email || !$pass)
    Kernel::fail('missing_fields', 'أدخل بريدك وكلمة المرور', 400);

$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
if (!check_rate_limit('login_' . md5($ip), 10, 300))
    Kernel::fail('rate_limit', 'حاول بعد 5 دقائق', 429);

try {
    $st = db()->prepare('SELECT * FROM users WHERE email = ? LIMIT 1');
    $st->execute([$email]);
    $u = $st->fetch();

    // Timing-safe: نستدعي password_verify دائماً لمنع enumeration عبر الوقت
    // حتى لو المستخدم غير موجود، الوقت يبقى ثابتاً (~100ms)
    $dummy_hash = '$2y$10$abcdefghijklmnopqrstuvuuuuuuuuuuuuuuuuuuuuuuuuuuuuu.';
    $hash_to_check = ($u && $u['password_hash']) ? $u['password_hash'] : $dummy_hash;
    $pass_ok = password_verify($pass, $hash_to_check);

    if (!$u || !$u['password_hash'] || !$pass_ok)
        Kernel::fail('invalid_credentials', 'البريد أو كلمة المرور غير صحيحة', 401);

    $token   = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', time() + SESSION_LIFETIME);
    db()->prepare('DELETE FROM sessions WHERE user_id = ? AND expires_at < NOW()')->execute([$u['id']]);
    db()->prepare('INSERT INTO sessions (user_id, token, expires_at) VALUES (?, ?, ?)')
        ->execute([$u['id'], hash('sha256', $token), $expires]);

    session_regenerate_id(true); // M6 FIX: Prevent session fixation attacks
    $_SESSION['user_id']       = $u['id'];
    $_SESSION['session_token'] = $token;
    session_write_close();

    json_response(['success' => true, 'user' => [
        'id'                => (int)$u['id'],
        'name'              => $u['name'],
        'email'             => $u['email'],
        'onboarding_done'   => (bool)$u['onboarding_done'],
        'subscription_tier' => $u['subscription_tier'],
        'learning_track'    => $u['learning_track'] ?: 'foundation',
        'rank_title'        => $u['rank_title'] ?: 'طالب جديد',
        'points_learn'      => (int)$u['points_learn'],
        'points_trade'      => (int)$u['points_trade'],
        'points_community'  => (int)$u['points_community'],
        'points_family'     => (int)$u['points_family'],
        'neighborhood_id'   => (int)$u['neighborhood_id'],
    ]]);

} catch (Throwable $e) {
    error_log('[login] ERROR: ' . $e->getMessage());
    Kernel::fail('server_error', 'حدث خطأ، حاول مجدداً', 500);
}
