<?php
include_once __DIR__ . '/../config/root_path.php';

require_once ROOT_PATH . 'api/core/response.php';
require_once ROOT_PATH . 'api/core/db.php';
require_once ROOT_PATH . 'api/core/mailer.php';
require_once ROOT_PATH . 'api/core/player.php';
require_once ROOT_PATH . 'api/middleware/requireAuth.php';
try {

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Method not allowed');
    }

    $uri = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
    $action = basename($uri);

    if ($action === 'me') {

        $player = requireAuth();
        jsonResponse(array_merge(
            ['success' => true],
            buildPlayerResponse($player, true)
        ));

    }

    $input = json_decode(file_get_contents('php://input'), true);
    if (!$input) {
        throw new Exception('Invalid JSON body');
    }

    /**
     * =========================
     * REGISTER (AS IS – TIDAK DIUBAH)
     * =========================
     */
    if ($action === 'register') {

        $email = filter_var($input['email'] ?? '', FILTER_VALIDATE_EMAIL);
        $password = $input['password'] ?? '';
        $confirm = $input['confirmPassword'] ?? '';
        $lang = $input['lang'] ?? 'id';

        if (!$email) {
            throw new Exception('Email tidak valid');
        }

        if (strlen($password) < 6) {
            throw new Exception('Password minimal 6 karakter');
        }

        if ($password !== $confirm) {
            throw new Exception('Password dan konfirmasi tidak sama');
        }

        $existing = fetchOne(
            "SELECT IDPlayer FROM player WHERE email = :email LIMIT 1",
            ['email' => $email]
        );

        if ($existing) {
            throw new Exception('Email sudah terdaftar');
        }

        $token = bin2hex(random_bytes(32));
        $passwordHash = password_hash($password, PASSWORD_BCRYPT);
        $expiredAt = date('Y-m-d H:i:s', strtotime('+48 hours'));

        execute("
            INSERT INTO email_logs (
                email,
                type,
                token,
                password_hash,
                is_read,
                is_used,
                expired_at,
                created_at
            ) VALUES (
                :email,
                'verify_register',
                :token,
                :password_hash,
                0,
                0,
                :expired_at,
                NOW()
            )
        ", [
            'email' => $email,
            'token' => $token,
            'password_hash' => $passwordHash,
            'expired_at' => $expiredAt
        ]);

        $verifyUrl = "{$domain_host}/api/public/verify-email.php?token={$token}";
        if ($g_sendEmail) {
            $result = sendMail(
                $email,
                'Verifikasi Email Anda',
                [
                    'type' => 'html',
                    'template' => 'verify_register.html',
                    'params' => [
                        'URLLinkVerifikasi' => $verifyUrl,
                        'NamaLengkap' => explode('@', $email)[0],
                        'EmailSentAt' => date('d M Y H:i')
                    ]
                ],
                [],
                $lang
            );

            if (!$result['success']) {
                throw new Exception('Gagal mengirim email');
            }
        }

        jsonResponse([
            'success' => true,
            'message' => 'Registrasi berhasil. Silakan cek email untuk verifikasi.'
        ]);
    }

    /**
     * =========================
     * LOGIN
     * =========================
     */
    if ($action === 'login') {

        $email = filter_var($input['email'] ?? '', FILTER_VALIDATE_EMAIL);
        $password = $input['password'] ?? '';

        if (!$email || !$password) {
            throw new Exception('Email atau password salah');
        }

        $player = getPlayerByEmail($email);

        if (
            !$player ||
            empty($player['password_hash']) ||
            !password_verify($password, $player['password_hash'])
        ) {
            throw new Exception('Email atau password salah');
        }

        $token = bin2hex(random_bytes(32)); // 64 char random
        $expiredAt = date('Y-m-d H:i:s', strtotime('+7 days'));

        execute("
            INSERT INTO auth_tokens (IDPlayer, token, expired_at)
            VALUES (:id, :token, :exp)
        ", [
            'id' => $player['IDPlayer'],
            'token' => $token,
            'exp' => $expiredAt
        ]);


        jsonResponse([
            'success' => true,
            'token' => $token,
            'user' => buildPlayerResponse($player, true)
        ]);

    }

    // -----------------------------------
    // FORGOT PASSWORD
    // -----------------------------------
    if ($action === 'forgot-password') {
        $email = filter_var($input['email'] ?? '', FILTER_VALIDATE_EMAIL);
        $lang = $input['lang'] ?? 'id';

        if (!$email) {
            throw new Exception('Email tidak valid');
        }

        // check if player exists (silently return success if not found)
        $player = getPlayerByEmail($email);
        if (!$player) {
            jsonResponse([
                'success' => true,
                'message' => 'If that email is registered, a reset link has been sent.'
            ]);
        }

        // generate token and insert log
        $token = bin2hex(random_bytes(32));
        $expiredAt = date('Y-m-d H:i:s', strtotime('+42 hours'));

        execute("
            INSERT INTO email_logs (
                email,
                type,
                token,
                is_read,
                is_used,
                expired_at,
                created_at
            ) VALUES (
                :email,
                'forgot_password',
                :token,
                0,
                0,
                :expired_at,
                NOW()
            )
        ", [
            'email' => $email,
            'token' => $token,
            'expired_at' => $expiredAt
        ]);

        $resetUrl = "{$domain_host}/api/public/reset-password.php?token={$token}";
        if ($g_sendEmail) {
            $result = sendMail(
                $email,
                'Reset Password',
                [
                    'type' => 'html',
                    'template' => 'forgot_password.html',
                    'params' => [
                        'URLLinkVerifikasi' => $resetUrl,
                        'NamaLengkap' => explode('@', $email)[0],
                        'EmailSentAt' => date('d M Y H:i')
                    ]
                ],
                [],
                $lang
            );

            if (!$result['success']) {
                throw new Exception('Gagal mengirim email');
            }
        }

        jsonResponse([
            'success' => true,
            'message' => 'Reset link sent.'
        ]);
    }

    throw new Exception('Invalid auth action');

} catch (Throwable $e) {
    jsonResponse([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
