<?php

namespace App\Http\Controllers;

use App\Models\Direction;
use App\Models\Student;
use App\Models\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Routing\Route;
use Illuminate\Support\Facades\DB;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
    protected $image = 'upload/image/';
    protected $image_url = 'https://clone.rateme.uz/public/upload/image/';
    protected $file = 'upload/file/';
    protected $file_url = 'https://clone.rateme.uz/public/upload/file/';

    public function __construct(Request $request, Route $route)
    {
        $permission = [
            'director' => [
                'UserController@view',
                'UserController@selectCommission',
                'UserController@status',
                'DirectionController@view',
                'DirectionController@select',
                'DirectionController@create',
                'GroupController@view',
                'GroupController@download',
                'GroupController@attach',
                'GroupController@import',
                'GroupController@create',
                'CommissionGroupController@view',
                'StudentController@view',
                'StudentController@download',
                'StudentController@create',
                'StudentBallController@view',
                'StudentBallController@info',
                'StudentBallController@editInfo',
                'StudentBallController@create',
                'Controller@delete',
            ],
            'admin' => [
                'AuthController@register',
                'UserController@view',
                'UserController@selectCommission',
                'UserController@status',
                'DirectionController@view',
                'DirectionController@select',
                'DirectionController@create',
                'GroupController@view',
                'GroupController@download',
                'GroupController@attach',
                'GroupController@import',
                'GroupController@create',
                'CommissionGroupController@view',
                'StudentController@view',
                'StudentController@download',
                'StudentController@create',
                'StudentBallController@view',
                'StudentBallController@info',
                'Controller@delete',
            ],
            'commission' => [
                'DirectionController@view',
                'DirectionController@select',
                'GroupController@view',
                'GroupController@download',
                'GroupController@import',
                'GroupController@create',
                'CommissionGroupController@view',
                'StudentController@view',
                'StudentController@download',
                'StudentBallController@view',
                'StudentBallController@info',
                'StudentBallController@create',
            ],
        ];

        $access = [
            'AuthController@login',
            'AuthController@resetPassword',
            'AuthController@loginCommission',
            'GroupController@download',
        ];

        $url = explode('\\', $route->getActionName())[3];

        if (in_array($url, $access)) {
            return true;
        }

        $id = explode('|', $request->bearerToken())[0];
        $auth = DB::table('personal_access_tokens')
            ->where('id', $id)
            ->first();
        if (!$auth) {
            $this->error('Sizga ruxsat yoq', 401);
        }
        $role = User::find($auth->tokenable_id)->role;
        $status = User::find($auth->tokenable_id)->status;
        if ($status == 0) {
            $this->error('Ruxsat aktiv emas', 403);
        }

        foreach ($permission as $key => $value) {
            if ($role == $key) {
                if (in_array($url, $value)) {
                    return true;
                }
            }
        }
        $this->error('Sizga Ruxsat yoq', 401);
    }

    protected function massiv($array, $index)
    {
        $json = [];
        if ($array) {
            foreach ($array as $arr) {
                $json[] = $arr[$index];
            }
        }

        return $json;
    }

    protected function array($array, $index)
    {
        if ($array && $array != '[]') {
            $i = 0;
            foreach ($array as $arr) {
                $massiv[$i] = $arr->$index;
                $i++;
            }
            return $massiv;
        }
        return [];
    }

    protected function array_group_by(array $data, $by_column)
    {
        $result = [];
        foreach ($data as $item) {
            $column = $item[$by_column];
            unset($item[$by_column]);
            $result[$column][] = $item;
        }
        return $result;
    }

    protected function checkRole($request, $role)
    {
        $id = explode('|', $request->bearerToken())[0];
        $auth = DB::table('personal_access_tokens')
            ->where('id', $id)
            ->first();
        $user = User::find($auth->tokenable_id);
        if ($user->role == $role) {
            return true;
        }
        $this->error('Ruxsat yoq', 401);
    }

    protected function getUser($request)
    {
        $id = explode('|', $request->bearerToken())[0];
        $auth = DB::table('personal_access_tokens')
            ->where('id', $id)
            ->first();
        return User::find($auth->tokenable_id);
    }

    protected function error($message, $type)
    {
        return abort(response()->json(['messege' => $message], $type));
    }

    protected function checkImage($image)
    {
        $data = ['JPG', 'PNG', 'JPEG', 'SVG'];
        if (
            filesize($image) < 1024 * 1024 &&
            in_array(strtoupper($image->extension()), $data)
        ) {
            return true;
        }
        return false;
    }

    protected function checkFile($file)
    {
        $data = ['MP4', 'MP3', 'AVI', 'MOV'];
        if (
            !in_array(strtoupper($file->extension()), $data)
        ) {
            return true;
        }
        return false;
    }

    protected function validationId($table, $id)
    {
        $value = DB::table($table)
            ->where('id', $id)
            ->first();
        if ($value) {
            return true;
        }
        $this->error(
            "$table tablitsasida bunday id lik ma'lumot topilmadi",
            400
        );
    }

    public function delete(Request $request, $type, $id)
    {
        $user = $this->getUser($request);

        if ($user->role == 'director') {
            if ($type == 'student') {
                $this->validationId('student', $id);

                $student = Student::find($id);

                $student->status = 'delete';

                $student->save();
                return response([
                    'message' => "Tinglovchi o'chirildi",
                ]);
            }
            $this->error('Sizga ruhsat yoq', 401);
        } elseif ($user->role == 'admin') {
            if ($type == 'student') {
                $this->validationId('student', $id);

                $student = Student::find($id);

                $student->status = 'delete';

                $student->save();
                return response([
                    'message' => "Tinglovchi o'chirildi",
                ]);
            } elseif ($type == 'direction') {
                $this->validationId('direction', $id);

                $direction = Direction::find($id);
                $direction->status = 'delete';

                $direction->save();

                return response([
                    'message' => "Yo'nalish o'chirildi",
                ]);
            } elseif ($type == 'commission') {
                $this->validationId('user', $id);
                $commis = User::find($id);

                if ($commis->role == 'commission') {
                    DB::table('personal_access_tokens')
                        ->where('tokenable_id', $id)
                        ->delete();
                    $commis->status = 'delete';
                    $commis->save();

                    return response([
                        'message' => "Komissiya o'chirildi",
                    ]);
                }
            }
        }
        $this->error('Sizga ruhsat yoq', 401);
    }

    protected function getMounthName($i)
    {
        switch ($i) {
            case '1':
                return 'Yanvar';
                break;
            case '2':
                return 'Fevral';
                break;
            case '3':
                return 'Mart';
                break;
            case '4':
                return 'Aprel';
                break;
            case '5':
                return 'May';
                break;
            case '6':
                return 'Iyun';
                break;
            case '7':
                return 'Iyul';
                break;
            case '8':
                return 'Avgust';
                break;
            case '9':
                return 'Sentyabr';
                break;
            case '10':
                return 'Oktyabr';
                break;
            case '11':
                return 'Noyabr';
                break;
            case '12':
                return 'Dekabr';
                break;
            case '13':
                return 'Yanvar';
                break;
        }
    }
}
