<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use Clevercherry\Backslash4\Controllers\Auth\LoginController;
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\UserController;
use Clevercherry\Backslash4\Backslash4;
 
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::group(['middleware' => 'web'], function() {
  //$config = Config::get('backslash4');
  $config = Backslash4::getDashboardConfig(); //either backslash4 or the tenent's version

  $prefix = @$config['adminPath'] ?? 'admin';
  // Admin Auth Routes
  Route::group(['prefix' => $prefix], function () {
              // Show the login form
      Route::get('login', [LoginController::class, 'create']);  //correct
      Route::post('login', [LoginController::class, 'authenticate'])->name('admin.login');
      Route::get('logout', [LoginController::class, 'logout'])->name('admin.logout');
  });

  $adminGuard = @$config['adminGuard'] ?? 'admin';
  $flatCmsMenu = Backslash4::getDashboardFlatCMS();

  if(!empty($flatCmsMenu))
  {
    //Route::group(['prefix' => $prefix, 'middleware' => 'auth'], function () use($config)
    Route::group(['prefix' => $prefix, 'middleware' => $adminGuard], function () use($flatCmsMenu)
    { 
      
      foreach($flatCmsMenu as $key => $item)
      {
        if(!empty($item) && !isset($item['html']))
        { 
          $model =  Str::singular($key);
          $controller = Str::singular($key) . 'Controller' ;
          $module = strtolower($key);
          if(isset($item['no-model']) && !empty($item['no-model']))
            $model = null;
          else
            $model = 'App\\Models\\'.$model;

          $autorouting = true;
          if(class_exists($model) && method_exists($model, 'hasStandardCMSRouting'))
          {
            // public static function hasStandardCMSRouting() :bool  { return true; }
            // above default in baseModel trait
            // hard code the routing in the model
            // return a flag to indicate if the CMS auto routing should also be included
            $autorouting = $autorouting && ($model)::hasStandardCMSRouting();
          }
          if($autorouting)
          {
              if($item['slug']=='/')
              { Route::get('/', 'App\Http\Controllers\Admin\\DashboardController@dashboard')
                      ->name('admin.dashboard');
              } else
              { 
                  Route::get($item['slug'], 'App\Http\Controllers\Admin\\'.$controller.'@index')
                        ->name('admin.'.$module.'.index');

                  Route::post($item['slug']."/index-ajax", 'App\Http\Controllers\Admin\\'.$controller.'@indexTable')
                        ->name('admin.'.$module.'.index.ajax');

                  Route::get($item['slug']."/create", 'App\Http\Controllers\Admin\\'.$controller.'@create')
                        ->name('admin.'.$module.'.create');
                  Route::post($item['slug']."/create", 'App\Http\Controllers\Admin\\'.$controller.'@store')
                        ->name('admin.'.$module.'.store');
                  Route::get($item['slug']."/edit/{id}", 'App\Http\Controllers\Admin\\'.$controller.'@edit')
                        ->name('admin.'.$module.'.edit');
                  Route::post($item['slug']."/update", 'App\Http\Controllers\Admin\\'.$controller.'@update')
                        ->name('admin.'.$module.'.update');
                  Route::get($item['slug']."/delete/{id}", 'App\Http\Controllers\Admin\\'.$controller.'@delete')
                        ->name('admin.'.$module.'.delete');
                  Route::get($item['slug']."/orderable/{id}/{direction}", 'App\Http\Controllers\Admin\\'.$controller.'@orderable')
                        ->name('admin.'.$module.'.orderable');

                  Route::get($item['slug']."/download/{id}/{field_name}", 'App\Http\Controllers\Admin\\'.$controller.'@download')
                        ->name('admin.'.$module.'.download');
                  
                  Route::get($item['slug']."/export", 'App\Http\Controllers\Admin\\'.$controller.'@export')
                        ->name('admin.'.$module.'.export');

                  if($controller=='SettingController')
                  {
                    Route::post($item['slug']."/savegroup", 'App\Http\Controllers\Admin\\'.$controller.'@saveGroupValues')
                        ->name('admin.'.$module.'.savegroup');
                  }

                  if($controller=='MediaManagerController')
                  {
                    Route::post($item['slug']."/rmdir", 
                                  'App\Http\Controllers\Admin\MediaManagerController@removeDir')
                            ->name('admin.mediamanager.rmdir');
                  }
              
        
                  if(class_exists($model) && ($model)::hasDuplicateRoute() )
                  {
                      Route::get($item['slug']."/duplicate/{id}", 'App\Http\Controllers\Admin\\'.$controller.'@duplicate')
                          ->name('admin.'.$module.'.duplicate');
                  } else
                  {
                      //fallbacks for PHQ3 special case will be replaced with above function returning true
                      if($controller=='HousetypeController' || $controller=='PlotController' || $controller=='CollectionController')
                      {
                          Route::get($item['slug']."/duplicate/{id}", 'App\Http\Controllers\Admin\\'.$controller.'@duplicate')
                              ->name('admin.'.$module.'.duplicate');
                      }
                  }
              }
          }  // end auto CMS routing
        }
      }
        
      //hardcoded routes
      Route::get('/apis/instagram-authentication', 'App\Http\Controllers\Admin\SettingController@instagramAuthentication')
                ->name('admin.apis.instagram.authentication');

      Route::post('/apis/google-geolocation', 'Clevercherry\Backslash4\Controllers\Admin\DashboardController@getGoogleLatLng')
                ->name('admin.apis.google.geolocation');

      Route::get("/download", 'App\Http\Controllers\Admin\DashboardController@downloadFileFromPath')
                  ->name('admin.dashboard.downloadpath'); //?file_path= as a get parameter


      if(true) //debug routes
      { // https://backslash4.local/admin/designs/
        Route::view('designs', 'backslash4::designs.index');
        
        Route::view('designs/all-components', 'backslash4::designs.all-components');
        Route::view('designs/dashboard', 'backslash4::designs.dashboard');
        Route::view('designs/listing', 'backslash4::designs.listing');

      }

    });
  }

  //uses adminBS4 so that js has a fixed place for admin ajax requests
  //Route::group(['prefix' => 'admin', 'middleware' => 'auth'], function () use($config)
  Route::group(['prefix' => 'adminBS4', 'middleware' => $adminGuard], function () use($config)
  { 
    Route::group(['prefix' => 'ajax'], function () use($config)
    { 
      Route::get("get-edit-block/{slug}", 'App\Http\Controllers\Admin\DashboardController@getEditBlock')
                      ->name('bs4.ajax.get-edit-block');
      Route::post("drop-file-upload", 'App\Http\Controllers\Admin\MediaManagerController@dropFileUpload')
                      ->name('bs4.ajax.drop-file-upload');
      Route::post("media-mkdir", 'App\Http\Controllers\Admin\MediaManagerController@makeDir')
                      ->name('bs4.ajax.media-mkdir');
      Route::get("media-getimages", 'App\Http\Controllers\Admin\MediaManagerController@getDirListing'); //debug
      Route::post("media-getimages", 'App\Http\Controllers\Admin\MediaManagerController@getDirListing')
                      ->name('bs4.ajax.media-getimages');
      Route::post("media-search-images", 'App\Http\Controllers\Admin\MediaManagerController@search')
                      ->name('bs4.ajax.media-search-images');
      Route::post('delete-file-url', 'App\Http\Controllers\Admin\MediaManagerController@deleteUrl')
                      ->name('bs4.ajax.media-deleteurl');
    });
  });

  if (config('backslash4.api.v1.enabled', 0)) {

    Route::group(['prefix' => 'api'], function ()
    { 
      //API routing
      Route::get('v1/{slug}', 'App\Http\Controllers\Admin\DashboardController@apiV1')
          ->where('slug', '.+')
          ->name('api.v1');
      
      Route::post('v1/{slug}', 'App\Http\Controllers\Admin\DashboardController@apiV1')
          ->where('slug', '.+');
    });
  }

  if (file_exists(public_path('/js/bs4-network-monitor.js'))) {
    // route for sending a network event
    Route::post('api/v1/network-event', 'App\Http\Controllers\Admin\DashboardController@networkEvent' )
        ->name('api.networkevent');
  }

  //fixed routes
  Route::get('/apis/response-instagram', 'App\Http\Controllers\Admin\SettingController@responseInstagram')
                ->name('apis.instagram.response');

  Route::get("/robots.txt", 'App\Http\Controllers\PageController@robots')
                      ->name('robots.index');

  //site map routes
  Route::get("/sitemap", 'App\Http\Controllers\PageController@sitemap');
  Route::get("/sitemap.xml", 'App\Http\Controllers\PageController@sitemap')
                      ->name('sitemap.xml');
  Route::get('/sitemap_index.xml', '\App\Http\Controllers\PageController@sitemap_index')
                      ->name('sitemap_index.xml');
  Route::get('/sitemap_{slug}.xml', '\App\Http\Controllers\PageController@sitemapPage')
                      ->name('sitemap_page.xml'); 

  // Route::get("/", 'App\Http\Controllers\PageController@index')
  //                    ->name('pages.home');

  Route::post('login', [UserController::class, 'authenticate'])->name('user.login');
  Route::get('logout', [UserController::class, 'logout'])->name('user.logout');

  // front end routes ---------------------------------------------------------
  if($config!=null)
  {
    foreach($flatCmsMenu as $key => $item)
    {
      if(!empty($item) && !isset($item['html']))
      {
        $model =  Str::singular($key);
        $controller = $model . 'Controller' ;
        $model = 'App\\Models\\'.$model;
            
        $autorouting = true;
        if(class_exists($model) && method_exists($model, 'provideRoutingAndFlag'))
        {
          // public static function provideRoutingAndFlag() :bool  { return true; }
          // above default in baseModel trait
          // hard code the routing in the model
          // return a flag to indicate if the front-end auto routing should also be included
          $autorouting = $autorouting && ($model)::provideRoutingAndFlag();
        }
        if($autorouting)
        {
            //automatic routing from the dashboard
            //with some optional options from the model

            $module = strtolower(Str::plural($key));
            if($module=='pages')
              $menuSlug='';
            else
              $menuSlug = $item['slug'];
            if(isset($item['fe-slug']) && !empty($item['fe-slug']))
              $menuSlug = $item['fe-slug'];

            $wildcardFlagIndex = false;
            $wildcardFlagItems = false;
            if($menuSlug!='0')
            { if(class_exists($model) && method_exists($model, 'getFrontEndRoute'))
              {   $indexSlug = ($model)::getFrontEndRoute($menuSlug.'/', true); 
                  $menuSlug = ($model)::getFrontEndRoute($menuSlug.'/{slug}', false);
                  //test for the bs4wildcard (here so that it's only done if we actually used the above functions)
                  $wildcardFlagIndex = Str::contains($indexSlug,'{bs4wildcard}');
                  $wildcardFlagItems = Str::contains($menuSlug,'{bs4wildcard}');
              } else
              {  //class or function does not exist
                $indexSlug = $menuSlug.'/';
                $menuSlug = $menuSlug.'/{slug}';
              }

              if(!empty($indexSlug))
              {
                  if($wildcardFlagIndex)
                  {
                      // you may want to validate the bs4wildcard parameter in your controller
                      Route::get($indexSlug, 'App\Http\Controllers\PageController@index')
                        ->where('bs4wildcard', '.+')
                        ->name($module.'.home');
                  } else {
                    Route::get($indexSlug, 'App\Http\Controllers\PageController@index')
                        ->name($module.'.home');
                  }
              }

              if(!empty($menuSlug))
              {
                  if($wildcardFlagItems)
                  {
                      // you may want to validate the bs4wildcard parameter in your controller
                      Route::get($menuSlug, 'App\Http\Controllers\\'.$controller.'@view')
                        ->where('bs4wildcard', '.+')
                        ->name($module.'.view');

                  } else {
                      Route::get($menuSlug, 'App\Http\Controllers\\'.$controller.'@view')
                        ->name($module.'.view');
                  }
              }
            }

        }
      }            
    }
  }
  
  if(config('backslash4.routes.CatchAllPageController', 1))
  {
    Route::get('{slug}', 'App\Http\Controllers\PageController@view')->where('slug', '.+')->name('pages.view');
  }
});
