<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Helpers\HelperController;
use App\Http\Controllers\Helpers\SMSController;
use App\Http\Controllers\Mails\EmailsController;
use App\Http\Resources\ChannelResource;
use App\Http\Resources\users\UsersResource;
use App\Models\User;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class UsersController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::with(['roles'])->latest()->get();
        return view('users.index', compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $roles = Role::all();
        $perms = Permission::all();
        return view('users.create', compact('roles', 'perms'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //validate
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email|unique:users,email',
            'phone' => 'required|unique:users,phone',
        ]);
        if ($validator->fails()) {
            $result = [
                'status' => 400,
                'errors' => $validator->errors()
            ];

            return response()->json($result, 400);
        }
        try {
            $name = $request->name;
            $email = $request->email;
            $phone = $request->phone;
            $password = Hash::make('Password');
            $role = $request->role;
            $notation = $request->notation;
            $plant_code = $request->plant_code ?? "";
            $company_code = $request->company_code ?? "";
            $check = UsersController::validations($request->notation, $request->plant_code, $request->company_code);
            if ($check && $check['status'] == 500) {
                $res = [
                    'status' => 500,
                    'message' => $check['message']
                ];
                return response()->json($res, 500);
            }

            //send an sms to newly created user to notify of new account creation
            SMSController::send_sms($phone, $text = "Dear ".$name." you account has been created successfully. Logins; email: ".$email." &  password: Password. Check your email to change your password");

            HelperController::save_plant_level($name, $email, $phone, $password, $role, $plant_code, $notation, $company_code);

            //email data
            
            // $code = sha1(time());
            // $root_url = route('index');
            // $url = $root_url . "/" . "reset_password/" . $code;
            // $message = 'Dear ' . $name . ', Welcome to unga group stock take software. Use the link below to set your password';
            // $subject = 'New Account';
            // $link_name = 'Set Password Link';

            //end of email data

            //send an email to the newly created user to set password
            // EmailsController::create_account($name, $email, $code, $url, $message, $subject, $link_name);

            $res = [
                'status' => 200,
                'message' => 'User created successfully.'
            ];
            return response()->json($res, 200);
        } catch (\Throwable $th) {
            $res = [
                'status' => 500,
                'message' => $th->getMessage()
            ];
            return response()->json($res, 500);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        try {
            $data = [
                'email' => $request->email,
                'phone' => $request->phone,
                'name' => $request->name,
                'plant_code' => $request->plant_code
            ];
            User::findOrFail($id)->update(array_merge($data));
            $res = [
                'status' => 200,
                'message' => 'User has been edited successfully!',
            ];
            return response()->json($res, 200);
        } catch (\Throwable $th) {
            $res = [
                'status' => 500,
                'message' => $th->getMessage(),
            ];
            return response()->json($res, 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        try {
            $user = User::findOrFail($id)->update(['status' => 'inactive']);
            $res = [
                'status' => 200,
                'message' => 'User deleted successfully!'
            ];
            return response()->json($res, 200);
        } catch (\Throwable $th) {
            $res = [
                'status' => 500,
                'message' => $th->getMessage()
            ];
            return response()->json($res, 500);
        }
    }

    public function fetch()
    {
        try {
            $users = User::all();
            $res = [
                'status' => 200,
                'users' => $users,
            ];
            return response()->json($res, 200);
        } catch (\Throwable $th) {
            $res = [
                'status' => 200,
                'users' => $th->getMessage(),
            ];
            return response()->json($res, 200);
        }
    }

    public function fetch_user_by_type(Request $request)
    {
        try {
            $role = $request->role;
            $users = User::where([['role', $role], ['status', 'active']])->with(['plants', 'companies'])->latest()->get();
            $res = [
                'status' => 200,
                'users' => UsersResource::collection($users),
            ];
            return response()->json($res, 200);
        } catch (\Throwable $th) {
            $res = [
                'status' => 500,
                'users' => $th->getMessage(),
            ];
            return response()->json($res, 500);
        }
    }

    public function update_password(Request $request)
    {
        $user = User::where('email', $request->email)->first();
        $user->update(['password' => Hash::make('Password')]);
        return 'Update successful';
    }

    public function fetch_channel_users($plant_code)
    {
        try {
            $users = User::where([['plant_code', $plant_code], ['role', '!=', 'plant_manager'], ['role', '!=', 'counting_clerk']])->get();
            $res = [
                'status' => 200,
                'channel_users' => ChannelResource::collection($users),
            ];
            return response()->json($res, 200);
        } catch (\Throwable $th) {
            $res = [
                'status' => 500,
                'message' => $th->getMessage()
            ];
            return response()->json($res, 500);
        }
    }

    static public function validations($notation, $plant_code, $company_code)
    {
        switch ($notation) {
            case 'plant_accountant':
                $check = User::where([['plant_code', $plant_code], ['role', 'plant_accountant'], ['status', 'active']])->first();
                if ($check) {
                    $res = [
                        'status' => 500,
                        'message' => 'This plant has already an active plant accountant called ' . $check->name,
                    ];
                    return $res;
                }
                # code...
                break;
            case 'plant_controller':
                $check = User::where([['plant_code', $plant_code], ['role', 'plant_controller'], ['status', 'active']])->first();
                if ($check) {
                    $res = [
                        'status' => 500,
                        'message' => 'This plant has already an active plant controller called ' . $check->name,
                    ];
                    return $res;
                }
                break;
            case 'plant_manager':
                $check = User::where([['plant_code', $plant_code], ['role', 'plant_manager'], ['status', 'active']])->first();
                if ($check) {
                    $res = [
                        'status' => 500,
                        'message' => 'This plant has already an active plant manager called ' . $check->name,
                    ];
                    return $res;
                }
                break;
            case 'inventory_accountant':
                $check = User::where([['role', 'inventory_accountant'], ['status', 'active']])->first();
                if ($check) {
                    $res = [
                        'status' => 500,
                        'message' => 'An active inventory accountant in the name of ' . $check->name . ', Company can only have one active inventory accountant',
                    ];
                    return $res;
                }
                break;
            case 'business_controller':
                $check = User::where([['company_code', $company_code], ['role', 'business_controller'], ['status', 'active']])->first();
                if ($check) {
                    $res = [
                        'status' => 500,
                        'message' => 'This company has already an active business controller called ' . $check->name,
                    ];
                    return $res;
                }
                break;
            case 'finance_controller':
                $check = User::where([['role', 'finance_controller'], ['status', 'active']])->first();
                if ($check) {
                    $res = [
                        'status' => 500,
                        'message' => 'An active finance controller in the name of ' . $check->name . ', Company can only have one active finance controller',
                    ];
                    return $res;
                }
                break;
            case 'general_manager':
                $check = User::where([['company_code', $company_code], ['role', 'general_manager'], ['status', 'active']])->first();
                if ($check) {
                    $res = [
                        'status' => 500,
                        'message' => 'This company already has na active GM called ' . $check->name,
                    ];
                    return $res;
                }
            default:
                # code...
                break;
        }
    }
}