<?php

namespace App\Facades;

use App\Models\Role;
use App\Models\User;
use App\Modules\Staff\Model\Staff;
use App\Modules\Useraction\Model\SaasAction;
use App\Modules\Useraction\Model\UserAction;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class General extends Facade
{

    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return 'general';
    }

    /*
     * Return boolean
     *
     * @return array
     * */

    static public function isSuperAdmin()
    {
        $guard       = auth()->guard(); // Retrieve the guard
        $sessionName = $guard->getName(); // Retrieve the session name for the guard
        $parts       = explode("_", $sessionName);
        unset($parts[count($parts) - 1]);
        unset($parts[0]);
        $guardName   = implode("_", $parts);

        return ($guardName == 'saas') ? true : false;
    }

    /**
     * Check if it is school teacher
     *
     * @return bool
     */
    public static function isSchoolTeacher()
    {
        return (Auth::user()->role_id == Role::ROLE_TEACHER) ? true : false;
    }

    /**
     * Check if it is school student
     *
     * @return bool
     */
    public static function isSchoolStudent()
    {
        return (Auth::user()->role_id == Role::ROLE_STUDENT) ? true : false;
    }

    /**
     * Check access of staff to see contact details
     *
     * @return mixed
     */
    public static function isStaffContactViewAccess()
    {
        return (new Staff())->where('user_id', Auth::user()->id)->pluck('view_contact')->first();
    }

    /**
     * Check access of staff to add/edit student details
     *
     * @return mixed
     */
    public static function isStaffStudentACL()
    {
        return (new Staff())->where('user_id', Auth::user()->id)->pluck('student_action')->first();
    }

    /**
     * Check if it is school Admin
     *
     * @return bool
     */
    public static function isSchoolAdmin()
    {
        return (Auth::user()->role_id == Role::ROLE_ADMIN) ? true : false;
    }

    /**
     * Log all saas user activity
     * Return  boolean
     * @param $activityId
     * @param array $options
     * @return bool
     */
    public static function saasLog($activityId, $options = [])
    {
        $disallowModules = [];
        if (isset($options['action_module']) && in_array($options['action_module'], $disallowModules))
        {
            return false;
        }

        SaasAction::setSaasUserActivity($activityId, $options);
    }

    /**
     * Log all user activity
     * Return  boolean
     * @param $activityId
     * @param array $options
     * @return bool
     */
    public static function userLog($activityId, $options = [])
    {
        $disallowModules = [];
        if (isset($options['action_module']) && in_array($options['action_module'], $disallowModules))
        {
            return false;
        }

        UserAction::setUserActivity($activityId, $options);
    }

    /**
     * Return Account Id
     *
     * @return int|mixed
     */
    public static function getAccountId()
    {
        return Config::get('account.id') ?? 0;
    }

    /**
     * Return User Id
     *
     * @return int
     */
    public static function getUserId()
    {
        return Auth::user()->id ?? 0;
    }

    /**
     * return the gender lists
     *
     * @return void
     */
    public static function getGender()
    {
        $optionValues           = [];
        $optionValues['male']   = 'Male';
        $optionValues['female'] = 'Female';

        return $optionValues;
    }

    /**
     * Return the blood groups data
     *
     * @return void
     */
    public static function getBloodGroups()
    {
        $optionValues         = [];
        $optionValues['male'] = 'A+';
        $optionValues['A-']   = 'A-';
        $optionValues['B+']   = 'B+';
        $optionValues['B-']   = 'B-';
        $optionValues['O+']   = 'O+';
        $optionValues['O-']   = 'O-';
        $optionValues['AB+']  = 'AB+';
        $optionValues['AB-']  = 'AB-';

        return $optionValues;
    }

    public static function getDataArray($modelName, $key = "id", $value = "title", $options = [])
    {
        if (isset($options["module_name"]))
        {
            $moduleName = $options["module_name"];
        }
        else
        {
            $moduleName = $modelName;
        }
        $modelName = "App\Modules\\" . $moduleName . "\\Model\\" . $modelName;
        if (class_exists($modelName))
        {
            $model  = new $modelName();
            $cols   = [$key, $value];
            $data   = $model->find(["cols" => $cols])->toArray();
            $result = array_column($data, $value, $key);
            return $result;
        }
        else
        {
            return [];
        }
    }

    /**
     * return the gender lists
     *
     * @return void
     */
    public static function getMaritalStatus()
    {
        $options = ["Single", "Married", "Widowed", "Separated", "Not Specified"];
        return array_combine($options, $options);
    }

    /**
     * return the list of week days
     *
     * @return void
     */
    public static function getWeekDays()
    {
        $options = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

        return array_combine($options, $options);
    }

    /**
     * return the list of week days
     *
     * @return void
     */
    public static function getFileCategory()
    {
        $options = ['Notes/Material', 'Homework', 'Assignment', 'Diagram', 'Question Set', 'Other'];

        return array_combine($options, $options);
    }

    /**
     * @param $request
     * @param $fileName
     * @return mixed
     */
    public static function uploadAvatar($request, $fileName)
    {
        try
        {
            $file  = $request->file($fileName);
            $path  = $file->hashName('avatars');
            $image = Image::make($file)->fit(150);
            Storage::disk('public')->put($path, (string) $image->encode());

            return $path;
        } catch (Exception $exception)
        {
            
        }
    }

    /**
     * Upload file to import data to storage
     *
     * @param $request
     * @param $fileName
     * @param $folderName
     * @return array|string
     */
    public static function uploadImportFile($request, $fileName, $folderName)
    {
        $validExtension = array("csv");
        // 2MB in Bytes
        $maxFileSize    = 2097152;

        if ($request->hasFile($fileName))
        {
            $file      = $request->file($fileName);
            // File Details
            $filename  = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $tempPath  = $file->getRealPath();
            $fileSize  = $file->getSize();
            $mimeType  = $file->getMimeType();

            if (!in_array(strtolower($extension), $validExtension))
            {
                return 'extension_not_match';
            }

            if ($fileSize > $maxFileSize)
            {
                return 'large_file_size';
            }

            $fileDetails = self::getImportedFileAccess($folderName);
            Storage::disk('public')->deleteDirectory($fileDetails['location']);
            Storage::disk('public')->put($fileDetails['location'] . '/' . $fileDetails['filename'], file_get_contents($file));

            return [
                'filename' => $fileDetails['filename'],
                'path'     => $fileDetails['path']
            ];
        }
    }

    /**
     * Configure storage directory
     *
     * @param $folderName
     * @return array
     */
    public static function getImportedFileAccess($folderName)
    {
        $location = 'uploads/' . Config::get('account.id') . '/' . $folderName;
        return [
            'filename' => "student_" . Config::get('account.id') . '_' . date('Y-m-d') . ".csv",
            'location' => $location,
            'path'     => 'app/public/' . $location
        ];
    }

    public static function uploadFileManager($request, $fileName, $folderName)
    {
        // 2MB in Bytes
        $maxFileSize = 2097152;

        if ($request->hasFile($fileName))
        {
            $file      = $request->file($fileName);
            // File Details
            $filename  = $file->getClientOriginalName();
            $extension = $file->getClientOriginalExtension();
            $tempPath  = $file->getRealPath();
            $fileSize  = $file->getSize();
            $mimeType  = $file->getMimeType();

            /* if ($fileSize > $maxFileSize) {
              return 'large_file_size';
              } */

            $location    = 'uploads/' . Config::get('account.id') . '/' . $folderName;
            $fileDetails = [
                'location' => $location,
                'path'     => 'app/public/' . $location
            ];
            $filename    = uniqid() . '.' . File::extension($filename);
            Storage::disk('public')->put($fileDetails['location'] . '/' . $filename, file_get_contents($file));

            return [
                'filename' => $filename,
                'path'     => $fileDetails['path']
            ];
        }
    }

    public static function getRoleNameById($role_id)
    {
        $roles = Role::getStaffRoles();
        if (isset($roles[$role_id]))
            return $roles[$role_id];
        return $role_id;
    }

}
