<?php

/** POST /api/auth/login */
route('POST', ['auth', 'login'], function () {
    Auth::throttle();
    $b     = Response::body();
    $email = trim(strtolower((string) ($b['email'] ?? '')));
    $pass  = (string) ($b['password'] ?? '');

    $u = DB::one(
        'SELECT u.*, r.code AS role FROM users u JOIN roles r ON r.id = u.role_id WHERE u.email = ?',
        [$email]
    );

    if (!$u || !$u['is_active'] || !password_verify($pass, $u['password_hash'])) {
        Auth::logAttempt($email, false, 'password');
        throw new ApiError('דוא"ל או סיסמה שגויים', 401);
    }
    if ($u['locked_until'] !== null && strtotime($u['locked_until']) > time()) {
        throw new ApiError('החשבון נעול זמנית. נסו שוב מאוחר יותר.', 423);
    }

    $needsOtp = (int) $u['twofa_enabled'] === 1 && $u['twofa_confirmed_at'] !== null;
    Auth::startSession((int) $u['id'], !$needsOtp);
    Auth::logAttempt($email, true, 'password');
    DB::run('UPDATE users SET last_login_at = NOW(), failed_attempts = 0 WHERE id = ?', [$u['id']]);

    // Enrollment is required but not completed yet.
    $needsEnroll = (int) $u['twofa_enabled'] === 1 && $u['twofa_confirmed_at'] === null;

    Response::json([
        'stage' => $needsOtp ? 'otp' : ($needsEnroll ? 'enroll' : 'ready'),
    ]);
});

/** POST /api/auth/verify-otp */
route('POST', ['auth', 'verify-otp'], function () {
    Auth::throttle();
    $u = Auth::partial();
    if (!$u) {
        throw new ApiError('פג תוקף ההתחברות, התחברו מחדש', 401);
    }
    $code = (string) (Response::body()['code'] ?? '');
    $row  = DB::one('SELECT twofa_secret_enc, twofa_secret_iv, twofa_secret_tag, twofa_last_counter
                     FROM users WHERE id = ?', [$u['id']]);
    if (!$row || $row['twofa_secret_enc'] === null) {
        throw new ApiError('לא הוגדר אימות דו-שלבי למשתמש זה', 400);
    }

    // A recovery code is accepted in place of an app code.
    if (strlen(preg_replace('/\s+/', '', $code)) > 8) {
        foreach (DB::all('SELECT id, code_hash FROM user_recovery_codes WHERE user_id = ? AND used_at IS NULL', [$u['id']]) as $rc) {
            if (password_verify(strtoupper(trim($code)), $rc['code_hash'])) {
                DB::run('UPDATE user_recovery_codes SET used_at = NOW() WHERE id = ?', [$rc['id']]);
                Auth::promote();
                Auth::logAttempt($u['email'], true, 'otp');
                Response::json(['ok' => true, 'used_recovery_code' => true]);
            }
        }
        Auth::logAttempt($u['email'], false, 'otp');
        throw new ApiError('קוד השחזור שגוי או נוצל כבר', 401);
    }

    $secret  = Crypto::decrypt($row['twofa_secret_enc'], $row['twofa_secret_iv'], $row['twofa_secret_tag']);
    $counter = Totp::verify($secret, $code);
    if ($counter === null) {
        Auth::logAttempt($u['email'], false, 'otp');
        throw new ApiError('הקוד שגוי או פג תוקפו', 401);
    }
    // Block replay of a code that was already used.
    if ($row['twofa_last_counter'] !== null && $counter <= (int) $row['twofa_last_counter']) {
        throw new ApiError('הקוד כבר נוצל. המתינו לקוד הבא באפליקציה.', 401);
    }
    DB::run('UPDATE users SET twofa_last_counter = ? WHERE id = ?', [$counter, $u['id']]);
    Auth::promote();
    Auth::logAttempt($u['email'], true, 'otp');
    Response::json(['ok' => true]);
});

/** GET /api/auth/me */
route('GET', ['auth', 'me'], function () {
    $u = Auth::partial();
    if (!$u) {
        Response::json(['authenticated' => false], 200);
    }
    Response::json([
        'authenticated' => Auth::twofaPassed(),
        'pending_otp'   => !Auth::twofaPassed(),
        'csrf'          => Auth::csrfToken(),
        'user'          => Auth::twofaPassed() ? $u : ['email' => $u['email'], 'full_name' => $u['full_name']],
        'config'        => [
            'whatsapp_number'    => (string) Config::setting('whatsapp_number', ''),
            'phone_country_code' => (string) Config::setting('phone_country_code', '972'),
        ],
    ]);
});

/** POST /api/auth/logout */
route('POST', ['auth', 'logout'], function () {
    Auth::destroy();
    Response::json(['ok' => true]);
});

/** POST /api/auth/change-password */
route('POST', ['auth', 'change-password'], function () {
    $u = Auth::require();
    $b = Response::body();
    $current = (string) ($b['current_password'] ?? '');
    $new     = (string) ($b['new_password'] ?? '');
    if (mb_strlen($new) < 10) {
        throw new ApiError('הסיסמה החדשה חייבת להכיל לפחות 10 תווים', 400);
    }
    $hash = (string) DB::value('SELECT password_hash FROM users WHERE id = ?', [$u['id']]);
    if (!password_verify($current, $hash)) {
        throw new ApiError('הסיסמה הנוכחית שגויה', 401);
    }
    DB::run('UPDATE users SET password_hash = ?, must_change_pass = 0 WHERE id = ?',
        [password_hash($new, PASSWORD_BCRYPT), $u['id']]);
    Response::json(['ok' => true]);
});

/**
 * POST /api/auth/2fa/setup
 * Generates a secret and returns the otpauth URI. The QR is rendered in the
 * browser, so the image never travels over the network.
 */
route('POST', ['auth', '2fa', 'setup'], function () {
    $u = Auth::partial();
    if (!$u) {
        throw new ApiError('נדרשת התחברות', 401);
    }
    $confirmed = DB::value('SELECT twofa_confirmed_at FROM users WHERE id = ?', [$u['id']]);
    if ($confirmed !== null && Auth::twofaPassed() === false) {
        throw new ApiError('האימות הדו-שלבי כבר מוגדר', 400);
    }

    $secret = Totp::generateSecret();
    [$ct, $iv, $tag] = Crypto::encrypt($secret);
    DB::run('UPDATE users SET twofa_secret_enc = ?, twofa_secret_iv = ?, twofa_secret_tag = ?,
             twofa_confirmed_at = NULL, twofa_last_counter = NULL WHERE id = ?',
        [$ct, $iv, $tag, $u['id']]);

    Response::json([
        'secret' => $secret,
        'uri'    => Totp::provisioningUri($secret, $u['email'], (string) Config::setting('totp_issuer', 'HelpDesk')),
    ]);
});

/** POST /api/auth/2fa/confirm */
route('POST', ['auth', '2fa', 'confirm'], function () {
    $u = Auth::partial();
    if (!$u) {
        throw new ApiError('נדרשת התחברות', 401);
    }
    $code = (string) (Response::body()['code'] ?? '');
    $row  = DB::one('SELECT twofa_secret_enc, twofa_secret_iv, twofa_secret_tag FROM users WHERE id = ?', [$u['id']]);
    if (!$row || $row['twofa_secret_enc'] === null) {
        throw new ApiError('התחילו את ההגדרה מחדש', 400);
    }
    $secret  = Crypto::decrypt($row['twofa_secret_enc'], $row['twofa_secret_iv'], $row['twofa_secret_tag']);
    $counter = Totp::verify($secret, $code);
    if ($counter === null) {
        throw new ApiError('הקוד שגוי. ודאו שהשעון במכשיר מסונכרן.', 400);
    }

    DB::run('UPDATE users SET twofa_enabled = 1, twofa_confirmed_at = NOW(), twofa_last_counter = ? WHERE id = ?',
        [$counter, $u['id']]);
    DB::run('DELETE FROM user_recovery_codes WHERE user_id = ?', [$u['id']]);

    $codes = [];
    for ($i = 0; $i < 8; $i++) {
        $c = strtoupper(bin2hex(random_bytes(5)));
        $codes[] = $c;
        DB::run('INSERT INTO user_recovery_codes (user_id, code_hash) VALUES (?,?)',
            [$u['id'], password_hash($c, PASSWORD_BCRYPT)]);
    }
    Auth::promote();
    Response::json(['ok' => true, 'recovery_codes' => $codes]);
});
