<?php
declare(strict_types=1);

$appPath = '/home/openaibd/openaibd_app';

require $appPath . '/bootstrap.php';
require $appPath . '/config/database.php';
require $appPath . '/app/Support.php';

use OpenAIBD\Services\AuthService;

header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: SAMEORIGIN');
header('Referrer-Policy: strict-origin-when-cross-origin');
header("Permissions-Policy: camera=(self), microphone=(self)");

$path = request_path();
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

if (
    $path === '/v1/chat/completions' &&
    $method === 'POST'
) {
    require_once $appPath .
        '/app/Controllers/DeveloperApiController.php';

    \OpenAIBD\Controllers\DeveloperApiController::
        chatCompletions();

    exit;
}


/*
 * ============================================================
 * PIN / UNPIN CHAT
 * ============================================================
 */
if (
    $path === '/api/conversation/pin' &&
    $method === 'POST'
) {
    header('Content-Type: application/json; charset=utf-8');

    if (!AuthService::check()) {
        http_response_code(401);
        echo json_encode([
            'ok' => false,
            'error' => 'Authentication required.'
        ]);
        exit;
    }

    verify_csrf();

    $uuid = trim((string) ($_POST['uuid'] ?? ''));

    if ($uuid === '') {
        http_response_code(422);
        echo json_encode([
            'ok' => false,
            'error' => 'Conversation UUID is required.'
        ]);
        exit;
    }

    $find = db()->prepare(
        'SELECT id, is_pinned
         FROM conversations
         WHERE uuid = ? AND user_id = ?
         LIMIT 1'
    );

    $find->execute([
        $uuid,
        AuthService::id()
    ]);

    $conversation = $find->fetch(PDO::FETCH_ASSOC);

    if (!$conversation) {
        http_response_code(404);
        echo json_encode([
            'ok' => false,
            'error' => 'Conversation not found.'
        ]);
        exit;
    }

    $newState =
        ((int) $conversation['is_pinned']) === 1 ? 0 : 1;

    $update = db()->prepare(
        'UPDATE conversations
         SET is_pinned = ?, updated_at = NOW()
         WHERE id = ?'
    );

    $update->execute([
        $newState,
        (int) $conversation['id']
    ]);

    echo json_encode([
        'ok' => true,
        'pinned' => (bool) $newState
    ]);

    exit;
}

if ($path === '/api/chat') {
    require $appPath . '/app/Controllers/ChatController.php';
    OpenAIBD\Controllers\ChatController::send();
}


if ($path === '/register') {
    require $appPath . '/app/Controllers/RegisterController.php';
    exit;
}

/*
 * ============================================================
 * OPENAI BD USER MODULE ROUTES
 * ============================================================
 */












/*
 * Open existing Recent / Pinned conversation
 */
if (
    preg_match(
        '#^/app/chat/([a-f0-9-]{36})$#i',
        $path,
        $matches
    )
) {
    if (!AuthService::check()) {
        redirect('/login');
    }

    require_once $appPath .
        '/app/Services/ConversationService.php';

    $conversation =
        \OpenAIBD\Services\ConversationService::findForUser(
            $matches[1],
            (int) AuthService::id()
        );

    if (!$conversation) {
        http_response_code(404);
        exit('Conversation not found.');
    }

    $_SESSION['current_conversation_id'] =
        (int) $conversation['id'];

    $_SESSION['current_conversation_uuid'] =
        (string) $conversation['uuid'];

    redirect('/app?conversation=' .
        rawurlencode((string) $conversation['uuid']));
}

if ($path === "/app/new" || $path === "/app/new/") {
    unset($_SESSION["current_conversation_id"]);
    redirect("/app?new=1");
}

if ($path === "/plans" || $path === "/plans/") {
    require $appPath . "/app/Controllers/PlansController.php";
    \OpenAIBD\Controllers\PlansController::show();
    exit;
}

if ($path === "/app/account" || $path === "/app/account/") {
    require $appPath . "/app/Controllers/AccountController.php";
    \OpenAIBD\Controllers\AccountController::show();
    exit;
}


if (
    ($path === '/app/developer' ||
     $path === '/app/developer/') &&
    $method === 'GET'
) {
    require_once $appPath .
        '/app/Models/ApiKey.php';

    require_once $appPath .
        '/app/Controllers/UserDeveloperController.php';

    \OpenAIBD\Controllers\UserDeveloperController::index();
    exit;
}

if (
    $path === '/app/developer/key/create' &&
    $method === 'POST'
) {
    require_once $appPath .
        '/app/Models/ApiKey.php';

    require_once $appPath .
        '/app/Controllers/UserDeveloperController.php';

    \OpenAIBD\Controllers\UserDeveloperController::createKey();
    exit;
}

if (
    $path === '/app/developer/key/action' &&
    $method === 'POST'
) {
    require_once $appPath .
        '/app/Models/ApiKey.php';

    require_once $appPath .
        '/app/Controllers/UserDeveloperController.php';

    \OpenAIBD\Controllers\UserDeveloperController::keyAction();
    exit;
}

if ($path === '/' && $method === 'GET') {
    require $appPath . '/app/Controllers/UserHomeController.php';
    exit;
}

if ($path === '/app' && $method === 'GET') {
    redirect('/');
}

if ($path === '/login' && $method === 'POST') {
    verify_csrf();

    $identity = trim((string) ($_POST['identity'] ?? ''));
    $password = (string) ($_POST['password'] ?? '');

    if ($identity === '' || $password === '') {
        flash('error', 'Email and password are required.');
        redirect('/login');
    }

    try {
        if (!AuthService::attempt($identity, $password)) {
            flash('error', 'Invalid login credentials.');
            redirect('/login');
        }

        redirect(
            AuthService::hasRole(
                'mother-admin',
                'admin',
                'sub-admin',
                'cashier',
                'support-staff'
            ) ? '/admin' : '/'
        );
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
        redirect('/login');
    }
}

if ($path === '/logout' && $method === 'POST') {
    error_log(
        'OPENAIBD LOGOUT HIT | redirect=' .
        (string) ($_POST['redirect_to'] ?? 'NONE')
    );

    verify_csrf();

    $logoutDestination = (string) ($_POST['redirect_to'] ?? '/');

    if (!in_array($logoutDestination, ['/', '/admin'], true)) {
        $logoutDestination = '/';
    }

    AuthService::logout();
    redirect($logoutDestination);
}

if ($path === '/login' && $method === 'GET') {
    if (AuthService::check()) {
        redirect(
            AuthService::hasRole(
                'mother-admin',
                'admin',
                'sub-admin',
                'cashier',
                'support-staff'
            ) ? '/admin' : '/'
        );
    }

    $error = flash('error');
    ?>
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport"
              content="width=device-width,initial-scale=1,viewport-fit=cover">
        <meta name="theme-color" content="#090b14">
        <title>Admin Login — OpenAI BD</title>
        <link rel="stylesheet" href="/assets/css/app.css?v=1">
    </head>
    <body class="auth-page">
        <main class="auth-shell">
            <section class="auth-card">
                <div class="brand-mark">O</div>
                <p class="eyebrow">OpenAI BD Control</p>
                <h1>Welcome back</h1>
                <p class="muted">
                    Sign in to manage your AI platform.
                </p>

                <?php if ($error): ?>
                    <div class="alert"><?= e($error) ?></div>
                <?php endif; ?>

                <form method="post" action="/login" class="auth-form">
                    <?= csrf_field() ?>

                    <label>
                        Email or phone
                        <input
                            type="text"
                            name="identity"
                            autocomplete="username"
                            required
                        >
                    </label>

                    <label>
                        Password
                        <input
                            type="password"
                            name="password"
                            autocomplete="current-password"
                            required
                        >
                    </label>

                    <button type="submit">Sign in securely</button>
                </form>
                <p class="auth-link">
                    New to OpenAI BD?
                    <a href="/register">Create a free account</a>
                </p>
            </section>
        </main>
    </body>
    </html>
    <?php
    exit;
}

if ($path === '/admin/users' && $method === 'GET') {
    require_once $appPath . '/app/Admin/UserAdminController.php';
    \OpenAIBD\Admin\UserAdminController::index();
    exit;
}

if ($path === '/admin/users/status' && $method === 'POST') {
    require_once $appPath . '/app/Admin/UserAdminController.php';
    \OpenAIBD\Admin\UserAdminController::updateStatus();
    exit;
}

if ($path === '/admin/plans' && $method === 'GET') {
    require_once $appPath . '/app/Admin/PlanAdminController.php';
    \OpenAIBD\Admin\PlanAdminController::index();
    exit;
}

if ($path === '/admin/plans' && $method === 'POST') {
    require_once $appPath . '/app/Admin/PlanAdminController.php';
    \OpenAIBD\Admin\PlanAdminController::save();
    exit;
}

if ($path === '/admin/ai-services' && $method === 'GET') {
    require_once $appPath . '/app/Admin/ProviderAdminController.php';
    \OpenAIBD\Admin\ProviderAdminController::index();
    exit;
}

if ($path === '/admin/ai-services/service' && $method === 'POST') {
    require_once $appPath . '/app/Admin/ProviderAdminController.php';
    \OpenAIBD\Admin\ProviderAdminController::service();
    exit;
}

if ($path === '/admin/ai-services/provider' && $method === 'POST') {
    require_once $appPath . '/app/Admin/ProviderAdminController.php';
    \OpenAIBD\Admin\ProviderAdminController::provider();
    exit;
}

if ($path === '/admin/ai-services/provider-health' && $method === 'POST') {
    require_once $appPath . '/app/Admin/ProviderAdminController.php';
    \OpenAIBD\Admin\ProviderAdminController::healthCheck();
    exit;
}

if ($path === '/admin/ai-services/model' && $method === 'POST') {
    require_once $appPath . '/app/Admin/ProviderAdminController.php';
    \OpenAIBD\Admin\ProviderAdminController::model();
    exit;
}

if ($path === '/admin/ai-services/route' && $method === 'POST') {
    require_once $appPath . '/app/Admin/ProviderAdminController.php';
    \OpenAIBD\Admin\ProviderAdminController::route();
    exit;
}


if ($path === '/admin/developer-api' && $method === 'GET') {
    require_once $appPath . '/app/Admin/DeveloperAdminController.php';
    \OpenAIBD\Admin\DeveloperAdminController::index();
    exit;
}

if (
    $path === '/admin/developer-api/key-action' &&
    $method === 'POST'
) {
    require_once $appPath .
        '/app/Admin/DeveloperAdminController.php';

    \OpenAIBD\Admin\DeveloperAdminController::keyAction();
    exit;
}

if ($path === '/admin/payments' && $method === 'GET') {
    require_once $appPath . '/app/Admin/PaymentAdminController.php';
    \OpenAIBD\Admin\PaymentAdminController::index();
    exit;
}

if ($path === '/admin/payment-gateways/update' && $method === 'POST') {
    require_once $appPath . '/app/Admin/PaymentAdminController.php';
    \OpenAIBD\Admin\PaymentAdminController::updateGateway();
    exit;
}

if ($path === '/admin/payments/review' && $method === 'POST') {
    require_once $appPath . '/app/Admin/PaymentAdminController.php';
    \OpenAIBD\Admin\PaymentAdminController::review();
    exit;
}

if ($path === '/admin/staff') {
    require $appPath . '/app/Admin/StaffAdminController.php';




    exit;
}
if ($path === '/admin' && $method === 'GET') {
    if (!AuthService::check()) {
        redirect('/login');
    }

    if (!AuthService::hasRole(
        'mother-admin',
        'admin',
        'sub-admin',
        'cashier',
        'support-staff'
    )) {
        http_response_code(403);
        exit('Access denied.');
    }

    $user = AuthService::user();

    if (!$user) {
        AuthService::logout();
        redirect('/login');
    }

    $stats = [
        'users' => (int) db()->query(
            'SELECT COUNT(*) FROM users'
        )->fetchColumn(),
        'staff' => (int) db()->query(
            "SELECT COUNT(DISTINCT ur.user_id)
             FROM user_roles ur
             INNER JOIN roles r ON r.id = ur.role_id
             WHERE r.slug IN
             ('mother-admin','admin','sub-admin','cashier','support-staff')"
        )->fetchColumn(),
        'roles' => (int) db()->query(
            'SELECT COUNT(*) FROM roles'
        )->fetchColumn(),
    ];
    ?>
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport"
              content="width=device-width,initial-scale=1,viewport-fit=cover">
        <meta name="theme-color" content="#090b14">
        <title>Mother Admin — OpenAI BD</title>
        <link rel="stylesheet" href="/assets/css/app.css?v=1">
    </head>
    <body class="dashboard-page">
        <aside class="sidebar">
            <div class="sidebar-brand">
                <span class="mini-logo">O</span>
                <strong>OpenAI BD</strong>
            </div>

            <nav>
                <a class="active" href="/admin">Overview</a>
                <a href="/admin/users">Users</a>
                <a href="/admin/staff">Staff Control</a>
                <a href="/admin/plans">Plans</a>
                <a href="/admin/payments">Payments</a>
                <a href="/admin/ai-services">AI Services</a>
                <a href="/admin/developer-api">Developer API</a>
                <a href="#">Agents</a>
                <a href="#">Affiliates</a>
                <a href="#">Settings</a>
            </nav>

            <form method="post" action="/logout">
                <?= csrf_field() ?>
                <input type="hidden" name="redirect_to" value="/admin">
                <button class="logout-button" type="submit">Sign out</button>
            </form>
        </aside>

        <main class="dashboard">
            <header class="topbar">
                <div>
                    <p class="eyebrow">Mother Admin</p>
                    <h1>Platform overview</h1>
                </div>
                <div class="account-chip">
                    <?= e($user['name']) ?>
                </div>
            </header>

            <section class="welcome-panel">
                <p>Welcome, <?= e($user['name']) ?>.</p>
                <h2>Your OpenAI BD control system is active.</h2>
            </section>

            <section class="stats-grid">
                <article>
                    <span>Total users</span>
                    <strong><?= $stats['users'] ?></strong>
                </article>
                <article>
                    <span>Staff accounts</span>
                    <strong><?= $stats['staff'] ?></strong>
                </article>
                <article>
                    <span>System roles</span>
                    <strong><?= $stats['roles'] ?></strong>
                </article>
            </section>
        </main>
    </body>
    </html>
    <?php
    exit;
}

http_response_code(404);
echo 'Page not found.';
