<?php
// Show errors during development - remove in production
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
define('BASE_PATH', __DIR__);
define('APP_PATH', BASE_PATH . '/app');

// Load helpers (session_start() is inside functions.php)
require_once APP_PATH . '/Helpers/functions.php';

// Check installation
$installed = file_exists(BASE_PATH . '/config/.installed');
$url       = isset($_GET['url']) ? trim($_GET['url'], '/') : '';
$segments  = explode('/', $url);
$route     = $segments[0] ?? '';

// Redirect to install if not installed
if (!$installed && $route !== 'install') {
    header('Location: /install');
    exit;
}

// Block install if already installed
if ($installed && $route === 'install') {
    header('Location: /');
    exit;
}

// Load config & DB if installed
$db = null;
if ($installed) {
    require_once BASE_PATH . '/config/config.php';
    require_once APP_PATH . '/Helpers/Database.php';
    $db = Database::getInstance();

    // Remember-me auto login
    if (empty($_SESSION['user_id']) && !empty($_COOKIE['remember_token'])) {
        try {
            $ru = $db->prepare("SELECT * FROM users WHERE remember_token = ? AND remember_expires > NOW() AND status = 'active' LIMIT 1");
            $ru->execute([$_COOKIE['remember_token']]);
            $ru = $ru->fetch();
            if ($ru) {
                $_SESSION['user_id']       = $ru['id'];
                $_SESSION['user_username'] = $ru['username'];
                $_SESSION['user_email']    = $ru['email'];
                $_SESSION['user_avatar']   = $ru['avatar'] ?? '';
            }
        } catch (\Exception $e) {
            // remember_token column not yet added — skip silently
        }
    }

    // License check — skip for install, api, and stream routes
    if (!in_array($route, ['install', 'api', 'stream', 'telegram'])) {
        require_once APP_PATH . '/Helpers/LicenseGuard.php';
        LicenseGuard::check($db);
    }
}
// ── Pre-routing: resolve /page/N for home, /search/page/N for search ──────────
// Home pagination: /page/2, /page/3 ...
if ($route === 'page' && isset($segments[1]) && ctype_digit($segments[1])) {
    require_once APP_PATH . '/Controllers/HomeController.php';
    $ctrl = new HomeController($installed ? $db : null);
    $ctrl->index((int)$segments[1]);
    exit;
}
// Search pagination: /search/page/2, /search/page/3 ...
if ($route === 'search' && ($segments[1] ?? '') === 'page' && isset($segments[2]) && ctype_digit($segments[2])) {
    require_once APP_PATH . '/Controllers/SearchController.php';
    $ctrl = new SearchController($db);
    $ctrl->index((int)$segments[2]);
    exit;
}

// Route
switch ($route) {
    case '':
    case 'home':
        require_once APP_PATH . '/Controllers/HomeController.php';
        $ctrl = new HomeController($installed ? $db : null);
        $ctrl->index(1);
        break;

    case 'anime':
        require_once APP_PATH . '/Controllers/AnimeController.php';
        $ctrl = new AnimeController($db);
        $slug = $segments[1] ?? '';
        $ctrl->detail($slug);
        break;

    case 'watch':
        require_once APP_PATH . '/Controllers/AnimeController.php';
        $ctrl      = new AnimeController($db);
        $watchSlug = $segments[1] ?? '';
        if (isset($segments[2]) && is_numeric($segments[2])) {
            $newUrl = '/watch/' . $segments[1] . '-episode-' . intval($segments[2]);
            header('Location: ' . $newUrl, true, 301);
            exit;
        }
        if (preg_match('/^(.+)-episode-(\d+)$/', $watchSlug, $m)) {
            $ctrl->watch($m[1], intval($m[2]));
        } else {
            http_response_code(404);
            require_once APP_PATH . '/Views/404.php';
        }
        break;

    case 'bookmarks':
        require_once APP_PATH . '/Controllers/BookmarkController.php';
        $ctrl = new BookmarkController($db);
        $ctrl->index();
        break;

    case 'search':
    require_once APP_PATH . '/Controllers/SearchController.php';
    $ctrl = new SearchController($db);
    $ctrl->index(max(1, (int)($_GET['page'] ?? 1)));  // ← read from $_GET
    break;

    // ═══════════════════════════════════════════════════════
    // STREAM ROUTE — hides real embed URLs from client
    // /stream/token          POST  → returns short-lived token
    // /stream/embed/{token}  GET   → validates token, redirects to real URL
    // ═══════════════════════════════════════════════════════
    case 'stream':
        require_once APP_PATH . '/Controllers/StreamController.php';
        $ctrl = new StreamController($db);
        $ctrl->handle($segments);
        break;

    case 'api':
        // ── Fast-path: progress tracker (no controller overhead) ──
        if (($segments[1] ?? '') === 'progress' && $_SERVER['REQUEST_METHOD'] === 'POST') {
            header('Content-Type: application/json');
            if (empty($_SESSION['user_id'])) { echo '{"ok":false}'; exit; }
            $body      = json_decode(file_get_contents('php://input'), true) ?? [];
            $userId    = (int)$_SESSION['user_id'];
            $animeId   = (int)($body['anime_id']   ?? 0);
            $episodeId = (int)($body['episode_id'] ?? 0);
            $progress  = (int)($body['progress']   ?? 0);
            if ($animeId && $episodeId && $progress > 0) {
                // UPDATE the most recent existing row first
                $upd = $db->prepare(
                    "UPDATE watch_history
                     SET progress_sec = ?, watched_at = NOW()
                     WHERE user_id = ? AND episode_id = ?
                     ORDER BY watched_at DESC
                     LIMIT 1"
                );
                $upd->execute([$progress, $userId, $episodeId]);
                // If no row existed yet, insert one
                if ($upd->rowCount() === 0) {
                    $db->prepare(
                        "INSERT INTO watch_history (user_id, anime_id, episode_id, progress_sec, watched_at)
                         VALUES (?, ?, ?, ?, NOW())"
                    )->execute([$userId, $animeId, $episodeId, $progress]);
                }
            }
            echo '{"ok":true}';
            exit;
        }
        require_once APP_PATH . '/Controllers/ApiController.php';
        $ctrl = new ApiController($installed ? $db : null);
        $action = $segments[1] ?? '';
        $ctrl->handle($action);
        break;

    case 'admin':
        require_once APP_PATH . '/Controllers/AdminController.php';
        $ctrl = new AdminController($db);
        $action = $segments[1] ?? 'dashboard';
        $ctrl->handle($action, $segments);
        break;

    case 'login':
        require_once APP_PATH . '/Controllers/AuthController.php';
        $ctrl = new AuthController($db);
        $ctrl->login();
        break;

    case 'logout':
        // Guard: if an admin session is active (and no user session), treat as admin logout
        if (!empty($_SESSION['admin_id']) && empty($_SESSION['user_id'])) {
            require_once APP_PATH . '/Controllers/AdminController.php';
            $ctrl = new AdminController($db);
            $ctrl->handle('logout', $segments);
        } else {
            require_once APP_PATH . '/Controllers/AuthController.php';
            $ctrl = new AuthController($db);
            $ctrl->logout();
        }
        break;

    // ═══════════════════════════════════════════════════════
    // USER ROUTES
    // ═══════════════════════════════════════════════════════
    case 'user':
        require_once APP_PATH . '/Controllers/AuthController.php';
        $ctrl = new AuthController($db);
        $sub  = $segments[1] ?? '';

        switch ($sub) {

            // ── Auth ──────────────────────────────────────────
            case 'login':    $ctrl->userLogin();    break;
            case 'register': $ctrl->userRegister(); break;
            case 'logout':   $ctrl->userLogout();   break;

            // ── Account settings ──────────────────────────────
            case 'change-password': $ctrl->userChangePassword(); break;

            // ── Firebase auth ─────────────────────────────────
            case 'firebase-auth': $ctrl->userFirebaseAuth(); break;

            // ── Profile edit (avatar upload) ──────────────────
            case 'update-profile': $ctrl->userUpdateProfile(); break;
            case 'update-avatar':  $ctrl->userUpdateAvatar();  break;
            case 'save-avatar':    $ctrl->userSaveAvatar();    break;

            // ── Watch history ops ─────────────────────────────
            case 'history':
                require_once APP_PATH . '/Controllers/BookmarkController.php';
                $histCtrl  = new BookmarkController($db);
                $historyOp = $segments[2] ?? '';
                switch ($historyOp) {
                    case 'delete': $histCtrl->historyDelete(); break;
                    case 'clear':  $histCtrl->historyClear();  break;
                    case 'import': $histCtrl->historyImport(); break;
                    default:
                        header('Content-Type: application/json');
                        echo '{"error":"Unknown history action"}';
                        exit;
                }
                break;

            // ── Membership / plans page ────────────────────────
            case 'membership':
                if (empty($_SESSION['user_id'])) {
                    redirect('/user/login?redirect=' . urlencode('/user/membership'));
                }
                require_once APP_PATH . '/Controllers/UserPaymentController.php';
                (new UserPaymentController($db))->membershipPage();
                break;

            // ── Checkout page ──────────────────────────────────
            case 'checkout':
                if (empty($_SESSION['user_id'])) {
                    redirect('/user/login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
                }
                require_once APP_PATH . '/Controllers/UserPaymentController.php';
                (new UserPaymentController($db))->checkoutPage();
                break;

            // ── Payment: submit request / status / lookup ──────
            case 'payment':
                if (empty($_SESSION['user_id'])) {
                    redirect('/user/login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
                }
                $payAction = $segments[2] ?? '';
                if ($payAction === 'request') {
                    require_once APP_PATH . '/Controllers/UserPaymentController.php';
                    (new UserPaymentController($db))->paymentRequest();
                } elseif ($payAction === 'status') {
                    require_once APP_PATH . '/Controllers/UserPaymentController.php';
                    (new UserPaymentController($db))->paymentStatus();
                } elseif ($payAction === 'lookup') {
                    require_once APP_PATH . '/Controllers/NowPaymentsController.php';
                    $npCtrl   = new NowPaymentsController($db);
                    $lookupOp = $segments[3] ?? '';
                    if ($lookupOp === 'alert' && $_SERVER['REQUEST_METHOD'] === 'POST') {
                        $npCtrl->userLookupAlert();       // POST → send Telegram alert
                    } else {
                        $npCtrl->userPaymentLookupPage(); // GET  → lookup page
                    }
                } else {
                    redirect('/user/membership');
                }
                break;

            // ── PayPal express checkout ────────────────────────
            case 'paypal':
                if (empty($_SESSION['user_id'])) {
                    redirect('/user/login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
                }
                require_once APP_PATH . '/Controllers/PayPalController.php';
                $ppCtrl   = new PayPalController($db);
                $ppAction = $segments[2] ?? '';
                switch ($ppAction) {
                    case 'create-order':    $ppCtrl->createOrder();   break;
                    case 'capture-order':   $ppCtrl->captureOrder();  break;
                    case 'success':         $ppCtrl->success();       break;
                    case 'payment-success': $ppCtrl->showSuccess();   break;
                    case 'cancel':          $ppCtrl->cancel();        break;
                    case 'diagnose':        $ppCtrl->diagnose();      break;
                    default:               redirect('/user/membership');
                }
                break;

            // ── NowPayments crypto checkout ────────────────────
            // POST /user/nowpayments/create-payment  → create invoice, get pay address
            // GET  /user/nowpayments/payment-status  → poll payment status
            // POST /user/nowpayments/ipn             → IPN webhook (server-to-server, NO login check)
            case 'nowpayments':
                $npAction = $segments[2] ?? '';
                require_once APP_PATH . '/Controllers/NowPaymentsController.php';
                $npCtrl = new NowPaymentsController($db);
                // IPN is called server-to-server by NowPayments — must NOT require login
                if ($npAction === 'ipn') {
                    $npCtrl->handleUser('ipn');
                } else {
                    if (empty($_SESSION['user_id'])) {
                        redirect('/user/login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
                    }
                    $npCtrl->handleUser($npAction);
                }
                break;

            // ── CoinPayments crypto checkout ───────────────────
            // POST /user/coinpayments/create-invoice  → create CP invoice, return pay address
            // GET  /user/coinpayments/invoice-status  → poll invoice state (JS poller)
            // POST /user/coinpayments/webhook         → CP webhook (server-to-server, NO login check)
            case 'coinpayments':
                $cpAction = $segments[2] ?? '';
                require_once APP_PATH . '/Controllers/UserCoinPaymentsController.php';
                $cpCtrl = new UserCoinPaymentsController($db);
                // Webhook is called server-to-server by CoinPayments — must NOT require login
                if ($cpAction === 'webhook') {
                    $cpCtrl->handle('webhook');
                } else {
                    if (empty($_SESSION['user_id'])) {
                        redirect('/user/login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
                    }
                    $cpCtrl->handle($cpAction);
                }
                break;

            // ── Indian & Global Payment Gateways ──────────────────
            // POST /user/indiapay/create-invoice      → create invoice, redirect to gateway
            // GET  /user/indiapay/return/{gateway}    → browser return after payment
            // POST /user/indiapay/{gateway}/webhook   → server IPN (NO login check)
            case 'indiapay':
                $igwAction = $segments[2] ?? '';
                $igwSub    = $segments[3] ?? '';
                require_once APP_PATH . '/Controllers/IndianPaymentController.php';
                $igwCtrl = new IndianPaymentController($db);
                $igwWebhooks = ['razorpay','paytm','payu','cashfree','ccavenue','instamojo','billdesk','stripe','easebuzz'];
                if (in_array($igwAction, $igwWebhooks) && $igwSub === 'webhook') {
                    $igwCtrl->handle($igwAction, $igwSub);
                } else {
                    if (empty($_SESSION['user_id'])) {
                        redirect('/user/login?redirect=' . urlencode($_SERVER['REQUEST_URI']));
                        break;
                    }
                    $igwCtrl->handle($igwAction, $igwSub);
                }
                break;

            default:
                redirect('/user/login');
        }
        break;

    // ── User profile ─────────────────────────────────────────
    case 'profile':
        require_once APP_PATH . '/Controllers/AuthController.php';
        $ctrl = new AuthController($db);
        $ctrl->profile();
        break;

    case 'install':
        require_once APP_PATH . '/Controllers/InstallController.php';
        $ctrl = new InstallController();
        $step = $segments[1] ?? '';
        $ctrl->handle($step);
        break;

    case 'az-list':
        require_once APP_PATH . '/Controllers/AZListController.php';
        $ctrl = new AZListController($db);
        $ctrl->index();
        break;

    case 'forgot-password':
        require_once APP_PATH . '/Controllers/AuthController.php';
        $ctrl = new AuthController($db);
        $ctrl->forgotPassword();
        break;

    case 'reset-password':
        require_once APP_PATH . '/Controllers/AuthController.php';
        $ctrl = new AuthController($db);
        $ctrl->resetPassword();
        break;

    case 'terms':
        require_once APP_PATH . '/Controllers/AuthController.php';
        $ctrl = new AuthController($db);
        $ctrl->showTerms();
        break;

    case 'privacy':
        require_once APP_PATH . '/Controllers/AuthController.php';
        $ctrl = new AuthController($db);
        $ctrl->showPrivacy();
        break;
        
    case 'sitemap.xml':
case 'sitemap':
    require_once APP_PATH . '/Controllers/SitemapController.php';
    $ctrl = new SitemapController($db);
    $ctrl->generate();
    break;    

    // ═══════════════════════════════════════════════════════
    // TELEGRAM WEBHOOK ROUTES
    // /telegram/webhook        POST → receive Telegram updates
    // /telegram/webhook/setup  GET  → register bot webhook URL
    // ═══════════════════════════════════════════════════════
    case 'telegram':
        $sub = $segments[1] ?? '';
        if ($sub === 'webhook') {
            require_once APP_PATH . '/Controllers/TelegramWebhookController.php';
            $ctrl   = new TelegramWebhookController($db);
            $action = $segments[2] ?? '';
            if ($action === 'setup') {
                $ctrl->setup();
            } else {
                $ctrl->handle();
            }
        } else {
            http_response_code(404);
            require_once APP_PATH . '/Views/404.php';
        }
        break;

    default:
        http_response_code(404);
        require_once APP_PATH . '/Views/404.php';
        break;
}