<?php
namespace Clevercherry\Backslash4\Controllers\Admin;

use App\Models\Block;
use App\Models\MediaManager;
use Illuminate\Http\Request;
use Clevercherry\Backslash4\Controllers\Controller;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use App\Models\Dashboard;
use App\Models\Setting;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Str;
use Clevercherry\Backslash4\Backslash4;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class DashboardController extends BkAdminController
{
    // public $adminView = 'backslash4::admin';  // uses generic
    public $adminRoute = 'admin.admins';
    public $AppModel = User::class;

    /**
     * Returns the index page view
     * @return type
     */
    public function dashboard()
    {
        return view('backslash4::admin.dashboard')
            ->with('widgets', $this->getAllWidgets())
            ->with('widgetSections', $this->getWidgetSections())
            ->with('dashboardStatistics', $this->getDashboardStatistics());
    }

    public function getAllWidgets() : Array
    {
        $widgets=[];
        //$config = Config::get('backslash4');
        //$config = Backslash4::getDashboardConfig(); //either backslash4 or the tenent's version
        $cmsMenu = Backslash4:: getDashboardFlatCMS(); //tenant aware
        foreach($cmsMenu as $menu => $item)
        {
            $defaultorder =90000;
            if(empty(@$item['no-model']) && !isset($item['html'])) // ie. 'no-model' != 1 or not set, and not an html spacer
            {
                $n = '\\App\\Models\\'.Str::singular($menu);

                $moduleWidgets = $n::getDashboardWidgets();
                if(!empty($moduleWidgets))
                    foreach ( $moduleWidgets AS $w )
                        $widgets[] = $w;
            }           
        }

        //sort the widget if there is a widget-order field
        usort($widgets, function ($a, $b) 
                        { return (@$a['widget-order'] ?? 999999999) <=> (@$b['widget-order'] ?? 999999999); 
                        });

        return $widgets;
    }


    /**
     * 
     */

    public function getWidgetSections() : Array
    {
        $widgetSections = [];

        $widgetSections = [
            // [
            //     'name' => 'analytics',
            //     'title' => 'Analytics',
            //     'text' => 'Lorem ipsum',
            //     'section-order' => 1
            // ],
            // [
            //     'name' => 'create',
            //     'title' => 'Create',
            //     'text' => 'Lorem ipsum',
            //     'section-order' => 2
            // ]
        ];

        usort($widgetSections, function ($a, $b) 
        { 
            return (@$a['section-order'] ?? 999999999) <=> (@$b['section-order'] ?? 999999999); 
        });

        return $widgetSections;
    }

    public function getDashboardStatistics() : String
    {
        return '';
    }

    public function getEditBlock($slug)
    {
        $block = new Block();
        $block->type = $slug;
        $block->active = true;

        return view('backslash4::components.bs-blocks.blockeditor-row')
                ->with('block', $block);
    }


    public function downloadFileFromPath(Request $request)
    {
        $fullpath = MediaManager::getStoragePath($request->file_path);
        if(Str::startsWith($request->file_path, 's3:'))
        {
            if(Storage::drive('s3')->exists($fullpath)){
                return Storage::drive('s3')->response($fullpath);
            }
        } else {
            if(File::exists($fullpath)) {
                return Storage::response($fullpath);
            }
        }

        return response(['error' => 'File not found, '.$request->file_path."\n ".$fullpath], 404);
    }

    public function getGoogleLatLng(Request $request)
    {
        $apiKey = Setting::getSetting('google-maps-api-key', 'AIzaSyCvkiQJWj3zoF3sV1PY7TAp_c5BIyyFRKk');// 'AIzaSyAOsDrtcuXqC_CQDp3ZYNDcSiQD_wobTIs');

        return Backslash4::getGoogleLatLng($request->address, $apiKey, false);
    }

}
