<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator as FacadesValidator;
use Nette\Utils\Random;

class AuthController extends Controller
{
    public function register(Request $request, $user_id = null)
    {
        if ($user_id) {
            $rules = [
                'name' => ['required', 'max:100'],
            ];
            $validator = FacadesValidator::make($request->all(), $rules);

            if ($validator->fails()) {
                $this->error($validator->errors(), 400);
            }
            $this->validationId('user', $user_id);
            $user = User::find($user_id);

            if (isset($request->phone) && "$request->phone" != "$user->phone") {
                $AuthorizationKey = 'YWltU01TOkFAaTJObSEyMzROZHM=';
                $phone = $request->phone;

                $phone_3 = substr($phone, 8, 3);
                $a = rand(100, 999);
                $b = rand(100, 999);

                $userConfCode = $phone_3 . '-' . $a . '-' . $b;
                $bazaCode = $phone_3 . $a . $b;

                $MSGID = date('Salom') . '' . rand(111, 999); //generateID like '191009102641261' -->> 19-10-09 10:26:41 rand:261
                if (
                    $request->role == 'commission' ||
                    (isset($request->type) && $request->type == 'rais')
                ) {
                    $MSGContent = 'rateme.uz Tasdiqlash kodi:' . $userConfCode;
                } else {
                    $MSGContent =
                        'rateme.uz Tasdiqlash kodi:' .
                        $userConfCode .
                        ' Login:' .
                        $phone;
                }

                $curl = curl_init();

                curl_setopt_array($curl, [
                    CURLOPT_URL => 'http://91.204.239.44/broker-api/send',
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 30,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'POST',
                    CURLOPT_POSTFIELDS => "{ 
                            \"messages\": 
                            [{
                            \"recipient\": \"$phone\",
                            \"message-id\": \"$MSGID\",
                            \"sms\": 
                            {
                                \"originator\": \"3700\",
                                \"content\": 
                                { 
                                    \"text\": \"$MSGContent\" 
                                } 
                            } 
                            }]
                            }",
                    CURLOPT_HTTPHEADER => [
                        'Authorization: Basic ' . $AuthorizationKey . '',
                        'Cache-Control: no-cache',
                        'Content-Type: application/json',
                    ],
                ]);

                $response = curl_exec($curl);
                $err = curl_error($curl);
                curl_close($curl);
                if ($err) {
                    return response([
                        'message' => 'cURL Error #:' . $err,
                    ]);
                } elseif ($response == 'Request is received') {
                    $user->name = $request->name;
                    $user->phone = $request->phone;
                    $user->password = bcrypt($bazaCode);
                    $user->updated_at = time();
                    if (isset($request->type)) {
                        $user->type = $request->type;
                    }
                    $user->save();

                    DB::table('personal_access_tokens')
                        ->where('tokenable_id', $user->id)
                        ->delete();

                    $user->createToken($user->name)->plainTextToken;

                    return response([
                        'message' => "Komissiya o'zgartirildi",
                    ]);
                }
                return response([
                    'message' => 'cURL Error #:' . $err,
                ]);
            }
            if (isset($request->type)) {
                $user->type = $request->type;
            }
            $user->name = $request->name;

            $user->save();

            return response([
                'message' => "Komissiya o'zgartirildi",
            ]);
        }
        $rules = [
            'name' => ['required', 'max:100'],
            'role' => ['required', 'max:20'],
            'phone' => ['required', 'unique:user', 'max:20'],
        ];
        $validator = FacadesValidator::make($request->all(), $rules);

        if ($validator->fails()) {
            $this->error($validator->errors(), 400);
        }
        // $request->validate([
        //      'name' => ['required', 'max:100'],
        //      'phone'=>['required','unique:user','max:20'],
        // ]);

        $AuthorizationKey = 'YWltU01TOkFAaTJObSEyMzROZHM=';
        $phone = $request->phone;

        $phone_3 = substr($phone, 8, 3);
        $a = rand(100, 999);
        $b = rand(100, 999);

        $userConfCode = $phone_3 . '-' . $a . '-' . $b;
        $bazaCode = $phone_3 . $a . $b;

        $MSGID = date('Salom') . '' . rand(111, 999); //generateID like '191009102641261' -->> 19-10-09 10:26:41 rand:261
        if (
            $request->role == 'commission' ||
            (isset($request->type) && $request->type == 'rais')
        ) {
            $MSGContent = 'rateme.uz Tasdiqlash kodi:' . $userConfCode;
        } else {
            $MSGContent =
                'rateme.uz Tasdiqlash kodi:' .
                $userConfCode .
                ' Login:' .
                $phone;
        }

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => 'http://91.204.239.44/broker-api/send',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => "{ 
                            \"messages\": 
                            [{
                            \"recipient\": \"$phone\",
                            \"message-id\": \"$MSGID\",
                            \"sms\": 
                            {
                                \"originator\": \"3700\",
                                \"content\": 
                                { 
                                    \"text\": \"$MSGContent\" 
                                } 
                            } 
                            }]
                            }",
            CURLOPT_HTTPHEADER => [
                'Authorization: Basic ' . $AuthorizationKey . '',
                'Cache-Control: no-cache',
                'Content-Type: application/json',
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
            return response([
                'message' => 'cURL Error #:' . $err,
            ]);
        } elseif ($response == 'Request is received') {
            $user = new User();
            $user->name = $request->name;
            $user->phone = $request->phone;
            $user->role = $request->role;
            $user->password = bcrypt($bazaCode);
            $user->created_at = time();
            $user->updated_at = time();
            if (isset($request->type)) {
                $user->type = $request->type;
            }
            $user->save();

            $user->createToken($user->name)->plainTextToken;

            return response([
                'message' => 'Komissiya yaratildi',
            ]);
        }
        return response([
            'message' => 'cURL Error #:' . $err,
        ]);

        $this->error('Parollarda moslik yoq', 429);
    }

    public function login(Request $request)
    {
        $rules = [
            'password' => ['required', 'min:5', 'max:20'],
            'phone' => ['required', 'max:20'],
        ];
        $validator = FacadesValidator::make($request->all(), $rules);

        if ($validator->fails()) {
            $this->error($validator->errors(), 400);
        }
        $user = User::where('phone', $request->phone)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            $this->error('Login yoki Parol xato', 401);
        }

        if ($user->status == 'passive') {
            $this->error('Ruxsat aktiv emas', 403);
        }

        if ($user->image) {
            $user->image = $this->image_url . $user->image;
        }

        DB::table('personal_access_tokens')
            ->where('tokenable_id', $user->id)
            ->delete();

        $token = $user->createToken($user->name)->plainTextToken;

        return response([
            'message' => 'Muvaffaqiyatli kirildi',
            'user' => $user,
            'Authorization' => $token,
        ]);
    }

    public function loginCommission(Request $request)
    {
        $rules = [
            'password' => ['required', 'min:5', 'max:20'],
        ];
        $validator = FacadesValidator::make($request->all(), $rules);

        if ($validator->fails()) {
            $this->error($validator->errors(), 400);
        }
        $users = User::where('role', '!=', 'admin')->get();

        foreach ($users as $user) {
            if (Hash::check($request->password, $user->password)) {
                if ($user->status == 'passive') {
                    $this->error('Ruxsat aktiv emas', 403);
                }

                if ($user->image) {
                    $user->image = $this->image_url . $user->image;
                }

                DB::table('personal_access_tokens')
                    ->where('tokenable_id', $user->id)
                    ->delete();

                $token = $user->createToken($user->name)->plainTextToken;

                if ($user->role == 'director') {
                    $user->role = 'commission';
                }

                return response([
                    'message' => 'Muvaffaqiyatli kirildi',
                    'user' => $user,
                    'Authorization' => $token,
                ]);
            }
        }
        $this->error('Parol xato', 401);
    }

    public function resetPassword(Request $request)
    {
        $user = User::where('phone', $request->phone)->first();
        if (!$user) {
            $this->error('Sizga ruxsat yoq', 401);
        }
        $AuthorizationKey = 'YWltU01TOkFAaTJObSEyMzROZHM=';
        $phone = $request->phone;

        $phone_3 = substr($phone, 8, 3);
        $a = rand(100, 999);
        $b = rand(100, 999);

        $userConfCode = $phone_3 . '-' . $a . '-' . $b;
        $bazaCode = $phone_3 . $a . $b;

        $MSGID = date('Salom') . '' . rand(111, 999); //generateID like '191009102641261' -->> 19-10-09 10:26:41 rand:261
        $MSGContent =
            'rateme.uz Tasdiqlash kodi:' . $userConfCode . ' Login:' . $phone;

        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => 'http://91.204.239.44/broker-api/send',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => "{ 
                            \"messages\": 
                            [{
                            \"recipient\": \"$phone\",
                            \"message-id\": \"$MSGID\",
                            \"sms\": 
                            {
                                \"originator\": \"3700\",
                                \"content\": 
                                { 
                                    \"text\": \"$MSGContent\" 
                                } 
                            } 
                            }]
                            }",
            CURLOPT_HTTPHEADER => [
                'Authorization: Basic ' . $AuthorizationKey . '',
                'Cache-Control: no-cache',
                'Content-Type: application/json',
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
            return response([
                'message' => 'cURL Error #:' . $err,
            ]);
        } elseif ($response == 'Request is received') {
            $users = User::where('phone', $request->phone)->get();

            foreach ($users as $user) {
                $user->password = bcrypt($bazaCode);
                $user->updated_at = time();

                $user->save();
            }

            return response([
                'message' => 'Kod yuborildi',
            ]);
        }
        return response([
            'message' => 'cURL Error #:' . $err,
        ]);
    }
}
