<?php

use CodeIgniter\Router\RouteCollection;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * @var RouteCollection $routes
 */
$routes->GET('/', 'Home::index');

// Admin Routes
$routes->GET('admin', 'Admin::index');
$routes->GET('admin/addTip', 'Admin::addTip');
$routes->POST('admin/saveTip', 'Admin::saveTip');
$routes->POST('admin/delete/(:num)', 'Admin::deleteTip/$1');
$routes->GET('admin/edit/(:segment)', 'Admin::editTip/$1');
$routes->POST('admin/update/(:segment)', 'Admin::update/$1');
$routes->GET('admin/viewTip/(:num)', 'Admin::viewTip/$1');
$routes->GET('admin/transactions', 'Admin::transactions');
$routes->GET('admin/stats', 'Admin::stats');
$routes->GET('admin/tips', 'Admin::tips');
$routes->GET('admin/tips/template', 'Admin::downloadTipsTemplate');
$routes->POST('admin/tips/import', 'Admin::importTips');
$routes->GET('admin/predictions', 'Admin::predictions');
$routes->POST('admin/mark-prediction/(:num)', 'Admin::markPrediction/$1');
$routes->POST('admin/mark-prediction/(:num)', 'Predictions::updateOutcome/$1');
$routes->GET('admin/author-stats', 'Admin::authorStats');
$routes->POST('admin/process-tip/(:num)', 'Admin::processTip/$1');
$routes->POST('admin/recalculate-stats', 'Admin::recalculateStats');
$routes->GET('admin/tips-unlock', 'Admin::tipsUnlock');
$routes->POST('admin/manual-unlock/(:segment)', 'Admin::manualUnlock/$1');
$routes->GET('admin/award-points', 'Admin::awardPointsView');
$routes->POST('admin/awardPoints', 'Admin::awardPoints');
$routes->GET('admin/user-points', 'Admin::userPoints');
$routes->GET('admin/predictions/tipster/(:segment)', 'Admin::getTipsterHistory/$1');
$routes->POST('admin/award-points-transaction/(:segment)', 'Admin::awardPointsFromTransaction/$1');
$routes->POST('admin/update-transaction-status/(:segment)', 'Admin::updateTransactionStatus/$1');
$routes->POST('admin/delete-failed-transactions', 'Admin::deleteFailedTransactions');
$routes->POST('admin/delete-expired-subscription-transactions', 'Admin::deleteExpiredSubscriptionTransactions');
$routes->POST('admin/award-pending-subscriptions', 'Admin::awardPendingSubscriptions');
$routes->GET('admin/cron/delete-expired-subscription-transactions', 'Admin::cronDeleteExpiredSubscriptionTransactions');
$routes->GET('admin/subscribers', 'Admin::subscribers');
$routes->GET('admin/plans', 'Admin::plans');
$routes->POST('admin/plans/save', 'Admin::savePlan');
$routes->GET('admin/plans/delete/(:num)', 'Admin::deletePlan/$1');
$routes->POST('admin/subscription/activate', 'Subscription::activateAfterPayment');
$routes->POST('admin/manual-subscription/(:segment)', 'Admin::manualSubscription/$1');
$routes->GET('admin/resetDailyHits', 'Admin::resetDailyHits');
$routes->POST('admin/deleteHitStats', 'Admin::deleteHitStats');
$routes->GET('admin/tip-sales', 'TipSales::adminView');
$routes->POST('admin/tip-sales/reset', 'TipSales::reset');
$routes->POST('admin/transaction/reconcile-missing-sales', 'TransactionChecker::reconcileMissingSales');
$routes->GET('admin/tip-sales/author/(:segment)', 'TipSales::authorSalesDetails/$1');
$routes->POST('admin/tip-sales/mark-settled', 'TipSales::markAsSettled');
$routes->POST('admin/tip-sales/settle-all/(:segment)', 'TipSales::settleAllForAuthor/$1');
$routes->GET('admin/tip-sales/settlement-history', 'TipSales::settlementHistory');
$routes->GET('admin/tip-sales/settlement-history/(:segment)', 'TipSales::settlementHistory/$1');
$routes->GET('admin/author-tickets/(:segment)', 'Admin::authorTickets/$1');
$routes->GET('admin/ticket-predictions/(:num)', 'Admin::ticketPredictions/$1');
$routes->GET('admin/author-list', 'Admin::authorList');
$routes->POST('admin/send-notification/(:num)', 'Admin::sendNotification/$1');
$routes->POST('admin/send-ticket-notification/(:num)', 'Admin::sendTicketNotification/$1');
$routes->GET('admin/app-version', 'Admin::appVersion');
$routes->POST('admin/app-version/update', 'Admin::updateAppVersion');

// Football catalog (admin)
$routes->GET('admin/football/settings', 'Admin::footballSettings');
$routes->POST('admin/football/settings', 'Admin::saveFootballSettings');
$routes->GET('admin/football/countries', 'FootballCatalog::countries');
$routes->GET('admin/football/leagues', 'FootballCatalog::leagues');
$routes->GET('admin/football/fixtures', 'FootballCatalog::fixtures');
$routes->POST('admin/football/sync-reference', 'FootballCatalog::syncReference');
$routes->POST('admin/football/sync-fixtures', 'FootballCatalog::syncFixturesCache');
$routes->POST('admin/football/sync-fixtures-batch', 'FootballCatalog::syncFixturesBatch');
$routes->GET('admin/cron/football-sync-reference', 'Admin::cronFootballSyncReference');
$routes->GET('admin/cron/football-sync-fixtures', 'Admin::cronFootballSyncFixtures');

// Bet Builder admin routes
$routes->GET('admin/bet-builder/matches', 'Admin::builderMatches');
$routes->POST('admin/bet-builder/matches/save', 'Admin::saveBuilderMatch');
$routes->POST('admin/bet-builder/matches/bulk-save', 'Admin::bulkSaveBuilderMatches');
$routes->POST('admin/bet-builder/matches/delete/(:num)', 'Admin::deleteBuilderMatch/$1');
$routes->POST('admin/bet-builder/matches/archive/(:num)', 'Admin::archiveBuilderMatch/$1');
$routes->POST('admin/bet-builder/matches/settle/(:num)', 'Admin::settleBuilderMatch/$1');
$routes->GET('admin/bet-builder/tickets', 'Admin::builderTickets');

// API Routes - Consolidated and organized better
$routes->group('api', ['filter' => 'cors'], function ($routes) {
    // Payment endpoints
    $routes->group('payments', function ($routes) {
        $routes->GET('/', 'Payments::getByPhone');
        $routes->GET('by-hash', 'Payments::getByHash');
        $routes->POST('process', 'Payments::process');
        $routes->POST('crypto', 'Payments::crypto');
        $routes->POST('finflo/create-session', 'Payments::finfloCreateSession');
        $routes->GET('finflo/callback', 'Payments::finfloCallback');
        $routes->GET('finflo/success', 'Payments::finfloSuccess');
        $routes->GET('finflo/cancel', 'Payments::finfloCancel');
        $routes->POST('pesapal/create-order', 'Payments::pesapalCreateOrder');
        $routes->GET('pesapal/status/(:segment)', 'Payments::pesapalStatus/$1');
        $routes->GET('by-ref', 'Payments::getByRef');
        $routes->GET('status/(:segment)', 'Payments::status/$1');
        $routes->GET('unlock-status/(:segment)/(:segment)', 'Payments::unlockStatus/$1/$2');
        $routes->POST('unlock-tip/(:segment)', 'Payments::unlockTip/$1');
        
        // Explicitly define allowed methods for listen endpoint
        $routes->match(['POST'], 'listen', 'Payments::status', ['as' => 'payments.listen']);
        
        // Add a specific handler for GET requests to show a clear error
        $routes->GET('listen', function() {
            return service('response')->setStatusCode(405)
                ->setHeader('Allow', 'POST')
                ->setJSON([
                    'success' => false,
                    'error' => 'Method Not Allowed. This endpoint only accepts POST requests.'
                ]);
        });
    });

    // Add a method not allowed handler
    $routes->setAutoRoute(false);

    // Tips endpoints
    $routes->group('tips', function ($routes) {
        $routes->GET('/', 'Tips::index');
        $routes->GET('(:segment)', 'Tips::show/$1');
        $routes->POST('/', 'Tips::create');
        $routes->put('(:segment)', 'Tips::update/$1');
        $routes->delete('(:segment)', 'Tips::delete/$1');
        $routes->GET('access/(:segment)/(:segment)', 'Tips::checkAccess/$1/$2');
        $routes->GET('check/(:num)', 'Tips::checkTipAvailability/$1');
    });

    // Predictions endpoints
    $routes->group('predictions', function ($routes) {
        $routes->GET('/', 'Predictions::index');
        $routes->GET('(:num)', 'Predictions::show/$1');
        $routes->POST('process-tip/(:num)', 'Predictions::processTip/$1');
        $routes->POST('process-all-tips', 'Predictions::processAllTips');
        $routes->PUT('update-outcome/(:num)', 'Predictions::updateOutcome/$1');
        $routes->PUT('(:num)', 'Predictions::update/$1');
        $routes->POST('update-score/(:num)', 'Predictions::updateScore/$1');
        $routes->POST('update-full/(:num)', 'Predictions::updateFull/$1');
        $routes->POST('extract-all', 'Predictions::extractAllPredictions');
        $routes->GET('yesterday-success-rate', 'Predictions::getYesterdaySuccessRate');
    });

    // Stats endpoints
    $routes->GET('author-stats', 'Predictions::getStats');
    $routes->GET('author-stats/(:segment)', 'Predictions::getAuthorStats/$1');
    $routes->GET('author/(:segment)', 'Tips::getTipsByAuthor/$1');
    $routes->GET('tipsters', 'Tips::getTipsters');
    $routes->GET('recalculate-stats', 'Predictions::recalculateAll');

    // Transaction endpoints
    $routes->group('transaction', function ($routes) {
        $routes->GET('check/(:segment)', 'TransactionChecker::checkTransaction/$1');
        $routes->GET('process-pending', 'TransactionChecker::processPendingTransactions');
        $routes->GET('cron', 'TransactionChecker::cronCheckPendingTransactions');
    });

    // Points endpoints
    $routes->group('points', function ($routes) {
        $routes->GET('(:segment)', 'Points::getPoints/$1');
        $routes->POST('redeem', 'Points::redeemPoints');
    });

    // Spin wheel endpoints
    $routes->group('spin', function ($routes) {
        $routes->POST('start', 'SpinWheel::start');
        $routes->POST('claim', 'SpinWheel::claim');
    });

    // Notification endpoints
    $routes->POST('dismiss-notification/(:num)', 'Admin::dismissNotification/$1');
    $routes->GET('get-notifications', 'Admin::apiGetNotifications');
    
    // FCM Notification endpoints
    $routes->group('notifications', function ($routes) {
        $routes->POST('register-token', 'Notifications::registerToken');
        $routes->POST('deactivate-token', 'Notifications::deactivateToken');
        $routes->POST('test-send', 'Notifications::testSend');
        $routes->GET('devices', 'Notifications::getDevices');
    });

    // Plans endpoints
    $routes->group('plans', function ($routes) {
        $routes->GET('/', 'Plans::index');
        $routes->POST('access', 'Plans::subAccess');
        $routes->POST('subscription-access', 'Plans::subscriptionAccess');
        $routes->POST('check-new-tips', 'Plans::checkNewTips');
        $routes->match(['GET', 'POST'], 'subscription-details', 'Plans::subscriptionDetails');
        $routes->GET('expiresub', 'Plans::expireDueSubscriptions');
    });

    // Bet Builder endpoints
    $routes->group('bet-builder', function ($routes) {
        $routes->GET('matches', 'BetBuilder::matches');
        $routes->POST('quote', 'BetBuilder::quote');
        $routes->POST('tickets', 'BetBuilder::create');
        $routes->GET('tickets', 'BetBuilder::tickets');
        $routes->GET('tickets/(:num)', 'BetBuilder::ticket/$1');
    });

    // Tips filtering endpoints
    $routes->GET('tips/subscriber', 'Tips::subscriberTips');
    $routes->GET('tips/regular', 'Tips::regularTips');

    // Tip sales endpoints
    $routes->group('tip-sales', function ($routes) {
        $routes->GET('/', 'TipSales::index'); // Admin: get all sales (last 7 days)
        $routes->POST('reset', 'TipSales::reset'); // Admin: reset sales
        $routes->GET('author', 'TipSales::authorSales'); // Author: get sales by PIN
    });

    // App version endpoint
    $routes->GET('app-version', 'AppVersion::index');
    $routes->POST('app-version/update', 'AppVersion::updateVersion');
});

// Auth Routes
$routes->GET('login', 'Auth::index');
$routes->POST('login', 'Auth::login');
$routes->GET('logout', 'Auth::logout');
$routes->GET('setup-pin', 'Auth::setupPin');

// Tipster Auth Routes
$routes->GET('tipster/login', 'TipsterAuth::index');
$routes->POST('tipster/login', 'TipsterAuth::login');
$routes->GET('tipster/logout', 'TipsterAuth::logout');

// Tipster Portal Routes (protected by TipsterAuthFilter)
$routes->group('tipster', ['filter' => 'tipsterAuth'], function($routes) {
    $routes->GET('/', 'Tipster::index');
    $routes->GET('add-tip', 'Tipster::addTip');
    $routes->POST('save-tip', 'Tipster::saveTip');
    $routes->GET('my-tips', 'Tipster::myTips');
    $routes->GET('edit-tip/(:num)', 'Tipster::editTip/$1');
    $routes->POST('update-tip/(:num)', 'Tipster::updateTip/$1');
    $routes->GET('sales', 'Tipster::sales');
    $routes->POST('validate-phone', 'Tipster::validatePhone');
    $routes->POST('withdraw', 'Tipster::withdraw');

    $routes->GET('football/countries', 'FootballCatalog::countries');
    $routes->GET('football/leagues', 'FootballCatalog::leagues');
    $routes->GET('football/fixtures', 'FootballCatalog::fixtures');
});

// Notification routes
$routes->GET('admin/notifications', 'Admin::notificationsView');
$routes->POST('admin/notifications/create', 'Admin::createNotification');
$routes->GET('admin/notifications/list', 'Admin::getNotifications');
$routes->POST('admin/notifications/dismiss/(:num)', 'Admin::dismissNotification/$1');

// Logging routes
$routes->group('', ['filter' => 'log'], function($routes) {
    // ... existing routes ...
});

// Custom 404 handler that returns JSON for API requests
$routes->set404Override(function() {
    $request = service('request');
    $response = service('response');
    
    // Check if it's an API request
    if (strpos($request->getPath(), 'api/') === 0 || 
        strpos($request->getHeaderLine('Accept'), 'application/json') !== false) {
        return $response->setStatusCode(404)
                       ->setJSON([
                           'status' => 404,
                           'message' => 'Not Found',
                           'path' => $request->getPath()
                       ]);
    }
    
    // For non-API requests, return the HTML view
    log_message('error', '404 Not Found: ' . current_url());
    return view('errors/html/error_404');
});

// Ensure payments process route is available for both tips and subscriptions
$routes->POST('admin/payments/process', 'Payments::process');


