<?php
use App\Http\Controllers\HomeController; // Make sure to import your controller
use App\Http\Controllers\DashboardController; // Make sure to import your controller
use App\Http\Controllers\AnalyticWebsiteController;
use App\Http\Controllers\AnalyticKeywordController;
use App\Http\Controllers\ContentController; // Make sure to import your controller
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\AccountController;
use App\Http\Controllers\LanguageController; // Import your controller
use App\Http\Controllers\StatusController; // Import your controller
use App\Http\Controllers\Auth\SocialController;
use Illuminate\Support\Facades\Auth;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

use Illuminate\Support\Facades\Route;
/*
use Spatie\Sitemap\Sitemap;
use Spatie\Sitemap\Tags\Url;
use App\Models\Post; // Example model

Route::get('/sitemaps/sitemap.xml', function () {
    $sitemap = Sitemap::create()
        ->add(Url::create('/')
            ->setLastModificationDate(now())
            ->setChangeFrequency(Url::CHANGE_FREQUENCY_DAILY)
            ->setPriority(1.0));

    return $sitemap->toResponse(request());
});
*/
// Route to change the language (accessible outside locale prefix)
Route::get('/change-locale/{locale}', [LanguageController::class, 'changeLocale'])->name('change.locale');

// redirect from old url to new subdomain
// This will handle the redirect from the main domain
Route::redirect('/tools', 'https://tools.seoezypro.com/', 301);

// If you need to redirect /abc/something to abc.example.com/something, use:
Route::get('tools/{path?}', function ($path = null) {
    $locale = App::getLocale();

/* for php8.x
    $langParam = match ($locale) {
        'th' => 'th-th',
        'en' => 'en-us',
        default => 'en-us',
    };
    */
    switch ($locale) {
        case 'th':
            $langParam = 'th-th';
            break;
        case 'en':
            $langParam = 'en-us';
            break;
        default:
            $langParam = 'en-us';
            break;
    }

    $mainDomain = 'seoezypro.com';

    // Ensure path has no leading slash
    $cleanPath = ltrim($path ?? '', '/');

    // Build full URL with lang query string
    $targetUrl = "https://tools.{$mainDomain}/{$cleanPath}";
    $targetUrl .= (str_contains($targetUrl, '?') ? '&' : '?') . "setlang={$langParam}";

    return redirect()->to($targetUrl, 301);
})->where('path', '.*');

Route::redirect('/index.html', '/'.app()->getLocale(), 301);
//Route::redirect('/dashboard', '/'.app()->getLocale().'/dashboard', 301);

/// Login with socialite //////
Route::get('/login/{provider}', [SocialController::class, 'redirect']);
Route::get('/login/{provider}/callback', [SocialController::class, 'callback']);
///////
Route::get('/', function () {
    $locale = substr(request()->server('HTTP_ACCEPT_LANGUAGE'), 0, 2);
    $locale = in_array($locale, ['en', 'th']) ? $locale : 'en';
    return redirect("/{$locale}");
});

Route::get('/search', function () {
    return view('search.results'); // This will render the Blade view for results
})->name('search.results');
////// Dashboard AJAX ////////
Route::post('/onchange/update-status', [StatusController::class, 'UpdateStatus'])->name('update-status.post');
//////////////////////////////
Route::group(['prefix' => '{locale}', 'middleware' => ['web', \App\Http\Middleware\SetLocale::class]], function () {

    ////////////////////// Front /////////////////////////
        Route::get('/', [HomeController::class, 'home'])->name('home');
        /*
        Route::get('/about-us', function () { // To shows about-us page
            return view('about-us');
        });
        Route::get('/contact-us', function () { // To shows contact-us page
            return view('contact-us');
        });
        */
        Route::get('/about-us', [HomeController::class, 'aboutUs'])->name('about-us');
/*        Route::get('/about-us', [ContentController::class, 'getContentDetail'])
            ->whereIn('type', ['about-us'])
            ->defaults('type', 'about-us')
            ->name('about-us');
*/
        Route::get('/contact-us', [HomeController::class, 'contactUsForm'])->name('contact-us');
/*
        Route::get('/{type}', [ContentController::class, 'getContentListByTypeFront'])->name('blog')
            ->defaults('type', 'blog'); // sets type automatically;
        Route::get('/{type}/{contentTitle}/{contentID}', [ContentController::class, 'getContentDetail'])->name('blog.detail')
            ->defaults('type', 'blog'); // sets type automatically;
*/

        Route::get('/{type}', [ContentController::class, 'getContentListByTypeFront'])
            ->whereIn('type', ['blog', 'news', 'article','about-us','faqs','service','privacy-policy'])
            ->defaults('type', 'blog')
            ->name('content.list');
        Route::get('/{type}/{contentTitle}/{contentID}', [ContentController::class, 'getContentDetail'])
            ->whereIn('type', ['blog', 'news', 'article','about-us','faqs','service','privacy-policy'])
            ->defaults('type', 'blog')
            ->name('content.detail');
/*
        Route::get('/blog', [ContentController::class, 'getContentListByTypeFront'])->name('blog')
            ->defaults('type', 'blog'); // sets type automatically;

        Route::get('/blog/{contentTitle}/{contentID}', [ContentController::class, 'getContentDetail'])->name('blog.detail')
            ->defaults('type', 'blog'); // sets type automatically;
*/
        // My account for User
        //Route::get('/myaccount', function () { return view('/myaccount/profile');})->name('myaccount');
        Route::get('/myaccount', [AccountController::class, 'showAccountProfileView'])->name('myaccount');
        //User login
        Route::get('/myaccount/login', [LoginController::class, 'showLoginForm'])->name('login');
        Route::post('/myaccount/login', [LoginController::class, 'login'])->name('login.post');
        //Route::post('/myaccount/login', [LoginController::class, 'login']);

        //Reset password
        Route::get('/myaccount/change-password', [AccountController::class, 'showChangePasswordForm'])->name('myaccount.reset-password');
        
        Route::get('/myaccount/newpassword/{token}', [AccountController::class, 'showPasswordResetForm'])->name('myaccount.newpassword');//form input new password
        Route::post('/myaccount/newpassword', [AccountController::class, 'saveResetPassword'])->name('myaccount.newpassword.post');//form input new password

        Route::get('/myaccount/reset-password', [AccountController::class, 'showResetPasswordForm'])->name('myaccount.reset-password');
        Route::post('/myaccount/reset-password', [AccountController::class, 'sendEmailRequestResetPassword'])->name('myaccount.reset-password.post'); // this is to validate   iul999iygggfvvvp   there is email
        //Register
        Route::get('/myaccount/register', [AccountController::class, 'showRegisterForm'])->name('myaccount.register');
        Route::post('/myaccount/register', [AccountController::class, 'saveAccountRegistered'])->name('myaccount.register.post');
        Route::get('/myaccount/profile', [AccountController::class, 'showAccountProfileView'])->name('myaccount.profile');
        Route::get('/myaccount/profile/edit', [AccountController::class, 'showAccountProfileEdit'])->name('profile.edit');
        Route::post('/myaccount/profile/{id}', [AccountController::class, 'saveAccountProfile'])->name('myaccount.profile.post');
        
         // route to sso to tools.seoezypro.com
        Route::get('/myaccount/sso_login', function (Request $request) {
            if (!Auth::check()) {
                return redirect(localized_route('login', ['redirect' => 'https://tools.seoezypro.com/admin'])); // Redirect to login if not authenticated
                //return response()->json(['error' => 'Unauthorized'], 401);
            }
        
            $key = env('JWT_SECRET');
            $userLocale = Auth::user()->locale ?? config('app.locale');  // get locale
            $payload = [
                'iss' => 'seoezypro.com',          // Issuer
                'sub' => Auth::id(),             // Subject (user ID)
                'email' => Auth::user()->email,  // User email $user = Auth::user(); // returns instance of Account if configured
                'rgp' => Auth::user()->groupId,  // User email $user = Auth::user(); // returns instance of Account if configured
                'locale' => $userLocale,        // to support multilanguage
                'iat' => time(),                 // Issued at
                'exp' => time() + 300            // Token expires in 5 mins
            ];
        
            $jwt = JWT::encode($payload, $key, 'HS256');
        //dd(request()->query('redirect'));
            // Redirect to subdomain with token (GET or POST)
            return redirect()->away("https://tools.seoezypro.com/account/sso-login?token={$jwt}");    
            
        })->name('sso_login');
        
        Route::get('/myaccount/sso_logout', function () {
            if (!Auth::check()) {
                return response()->json(['error' => 'Unauthorized'], 401);
            }
        
            // Redirect to subdomain with token (GET or POST)
            return redirect()->away("https://tools.seoezypro.com/account/signout");    
            
        })->name('sso_logout');

        // email out to use
        // need one page to confirm successfully or unsuccessfully
        Route::get('/emails/validation', [MailingList::class, 'sendEmailPreparing'])->name('sendemail.validation'); // all page need to send out email, need to be get approve from this page. If TRUE then sent, if FALSE then not sent. Afterthat, return to page requested.
        Route::post('/emails/email-verification', [MailingList::class, 'sendEmailPreparing'])->name('sendemail.email-verification');//already save to DB then sent email link to user and need to click on email back to confirm
        Route::get('/emails/login', [MailingList::class, 'sendEmailPreparing'])->name('sendemail.login');
        Route::get('/emails/change-password', [MailingList::class, 'sendEmailPreparing'])->name('sendemail.change-password');
        Route::get('/emails/reset-password', [MailingList::class, 'sendEmailPreparing'])->name('sendemail.reset-password');
        Route::get('/emails/delete-account', [MailingList::class, 'sendEmailPreparing'])->name('sendemail.delete-account');
        Route::post('/emails/reset-password', [MailingList::class, 'sendEmailPreparing'])->name('sendemail.reset-password');
        
        Route::post('/emails/successfully', [MailingList::class, 'sendEmailPreparing'])->name('sendemail.successfully');// any email succesfully
        Route::post('/emails/unsuccessfully', [MailingList::class, 'sendEmailPreparing'])->name('sendemail.unsuccessfully');// any email unsuccesfully
        
        /////////////////////////// Dashboard /////////////////////////////
        //dashboard
        Route::get('/dashboard', [DashboardController::class, 'index'])->name('dashboard.index');
        //Dashboard news management Add, Edit, Delete or/and Settings.
        Route::get('/dashboard/content', [ContentController::class, 'getContentListByType'])->name('dashboard.admin.content.index');
        Route::get('/dashboard/content/contact-us', [DashboardController::class, 'getContactUsForm'])->name('dashboard.admin.contact-us');
        //type
        Route::get('/dashboard/content/type', [DashboardController::class, 'getTypeList'])->name('dashboard.admin.content.type');
        Route::post('/dashboard/content/type', [DashboardController::class, 'saveTypeList'])->name('dashboard.admin.content.type.post');
        Route::get('/dashboard/content/type/{typeID}', [DashboardController::class, 'showUpdateTypeForm'])->name('dashboard.admin.content.type.update');
        Route::post('/dashboard/content/type/delete', [DashboardController::class, 'deleteType'])->name('dashboard.admin.content.type.delete');
        
        //category
        Route::get('/dashboard/content/category', [DashboardController::class, 'getCategoryList'])->name('dashboard.admin.content.category');
        Route::post('/dashboard/content/category', [DashboardController::class, 'saveCategoryList'])->name('dashboard.admin.content.category.post');
        Route::get('/dashboard/content/category/{categoryID}', [DashboardController::class, 'showUpdateCategoryForm'])->name('dashboard.admin.content.category.update');
        Route::post('/dashboard/content/category/delete', [DashboardController::class, 'deleteTypeCategory'])->name('dashboard.admin.content.category.delete');

        //content
        Route::get('/dashboard/content/all', [ContentController::class, 'getContentListByType'])->name('dashboard.admin.content.index.all');
        Route::get('/dashboard/content/all/{type?}', [ContentController::class, 'getContentListByType'])->name('dashboard.admin.content.index.all');
        Route::post('/dashboard/content/', [DashboardController::class, 'saveTypeList'])->name('dashboard.admin.content.index.post');
        Route::get('/dashboard/content/contentUpdate/{contentID}', [ContentController::class, 'showUpdateContentForm'])->name('dashboard.admin.content.index.edit');
        Route::post('/dashboard/content/delete', [ContentController::class, 'deleteContent'])->name('dashboard.admin.content.index.delete');
        ////
        //content about-us
        //Route::get('/dashboard/content/edit/{contentID}', [DashboardController::class, 'showUpdateContentForm'])->name('dashboard.admin.content.index.edit');////// waiting to set about-us id
        ////////////////////////////////////////////////////////////////
        //Dashboard service
        Route::get('/dashboard/accounts', [AccountController::class, 'getAllUsers'])->name('dashboard.admin.accounts.accounts');
        Route::post('/dashboard/accounts', [AccountController::class, 'getAllUsers'])->name('dashboard.admin.accounts.accounts.post');
        Route::get('/dashboard/accounts/unverified', [AccountController::class, 'getAllUsersUnverified'])->name('dashboard.admin.accounts.unverified');
        Route::get('/dashboard/accounts/blacklist', [AccountController::class, 'getAllUsersBlackListฺ'])->name('dashboard.admin.accounts.blacklist');
        Route::get('/dashboard/accounts/profile', [AccountController::class, 'showAccountProfileView'])->name('dashboard.admin.accounts.profile');
        Route::get('/dashboard/accounts/edit-profile', [AccountController::class, 'showAccountProfileView'])->name('dashboard.admin.accounts.profile.edit');
        Route::get('/dashboard/accounts/delete-profile', [AccountController::class, 'deleteAccountProfile'])->name('dashboard.admin.accounts.profile.delete');
        Route::get('/dashboard/accounts/activity', [AccountController::class, 'getAccountHistory'])->name('dashboard.accounts.activity');
        Route::get('/dashboard/accounts/history', [AccountController::class, 'getAccountHistory'])->name('dashboard.accounts.history');
        Route::get('/dashboard/analytic', [DashboardController::class, 'showAnalytic'])->name('dashboard.analytic');
        ///Analytics Website
        Route::get('/dashboard/analytic/websites', [AnalyticWebsiteController::class, 'showWebsitesForm'])->name('dashboard.websites');
        Route::post('/dashboard/analytic/websites', [AnalyticWebsiteController::class, 'SaveWebsites'])->name('dashboard.websites.post');
        Route::get('/dashboard/analytic/websites/update/{domain}', [AnalyticWebsiteController::class, 'showUpdateWebsiteForm'])->name('dashboard.websiteUpdate');
        Route::post('/dashboard/analytic/websites/delete', [AnalyticWebsiteController::class, 'deleteWebsite'])->name('dashboard.websiteDelete');

        ///Analytics Keyword
        Route::get('/dashboard/analytic/keywords', [AnalyticKeywordController::class, 'showKeywordsForm'])->name('dashboard.keywords');
        Route::post('/dashboard/analytic/keywords', [AnalyticKeywordController::class, 'SaveKeywords'])->name('dashboard.keywords.post');
        Route::get('/dashboard/analytic/keywords/update/{keyword}', [AnalyticKeywordController::class, 'showUpdateKeywordForm'])->name('dashboard.keywordUpdate');
        Route::post('/dashboard/analytic/keywords/delete', [AnalyticKeywordController::class, 'deleteKeyword'])->name('dashboard.keywordDelete');

        ////
        Route::get('/dashboard/history', [DashboardController::class, 'showHistory'])->name('dashboard.account.history');
        Route::get('/dashboard/news', [DashboardController::class, 'showDashboardNews'])->name('dashboard.news');
        Route::get('/dashboard/document', [DashboardController::class, 'showDashboardDocument'])->name('dashboard.document');
        //////
        Route::get('/myaccount/logout', [LoginController::class, 'logout'])->name('logout');
        Route::post('/myaccount/logout', [LoginController::class, 'logout'])->name('logout.post');
        
});
