<?php

namespace App\Http\Controllers;
use App\Utilities\ApiCalls;
use App\Utilities\SmsLibrary;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\UserAccountsMail;
use App\Mail\PasswordResetMail;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use App\Rules\GhanaPhoneRule;
use Illuminate\Support\Facades\Hash;

class UsersController extends Controller
{
    public function index(){
        $data = [
            'page_title' => 'Users Page '
        ];
        return view('users.index', $data);
    }
    public function reset(){
        $data = [
            'page_title' => 'Password Reset Page'
        ];
        return view('user-auth.reset', $data);
    }
    public function check_reset_email(Request $request){
        dd($request->all());
        // array:2 [▼ // app/Http/Controllers/UsersController.php:31
        //   "_token" => "ihqMhlBqQp6WP0qNr6mx9ddqF1szemeyHbjcsFtS"
        //   "email" => "kwesi_banson@hotmail.com"
        // ]
        
        $url = "user_mgt/get_user_by_email.php";
        $user_id = "34ba702b-18f8-4d85-948d-8c55e8500f32";
        $data = json_encode([
            'user_id' => "34ba702b-18f8-4d85-948d-8c55e8500f32",// $id,
            'api_token' => env('LUPMISAPIKEY')// make the API token a constant
        ]);
        $result = ApiCalls::CurlPost($data, $url);
        $result = json_decode($result, true);

        // dd($result);
        $recipientEmail = $result['data']['email'];
        $fullname = $result['data']['full_name'];
        $phone = $result['data']['phone'];
        //send reset link email 
        //baduhupir@mailinator.com
        $reset_link = env('APP_URL') . "/reset-auth/" . $user_id;
        if(env('APP_ENV') == 'production'){
            Mail::to($recipientEmail)->send(new PasswordResetMail($fullname, $reset_link));
        }
        return redirect(url('reset-notice')); //get
        // return redirect(url('new-password-form'));
        
    }
    public function reset_notice(Request $request){

        
        return view('user-auth.email-notice');

    }
    public function show_new_passform(Request $request){
        // code...show_new_passform
        // dd('foo bar show new pass');
        $data = [
            'page_title' => 'New Password Form'
        ];
        return view('user-auth.password', $data);
    }

    public function handle_reset(Request $request){
        $url = "user_mgt/update_usr_user.php";
        $user_data = [
            
            'user_id' => $request['user_id'],
            'api_token' => env('LUPMISAPIKEY'),
        ];
        $data = json_encode($user_data);
        $result = ApiCalls::CurlPost($data, $url);
        $result = json_decode($result, true);
        // dd($result);
        // return response()->json($result);
        if ($request->expectsJson()) {
            return response()->json($result);
        }
        return redirect(url('reset-success')); //get
    }
    public function reset_success(Request $request){
        // code...show_new_passform
        // dd('foo bar handle reset');

        $data = [
            'page_title' => 'New Password Success'
        ];
        return view('user-auth.password-success', $data);
    }

    public function edit($id){
        $url = "user_mgt/get_user_by_user_id.php";

        $data = json_encode([
            'user_id' => $id,
            'api_token' => env('LUPMISAPIKEY')// make the API token a constant
        ]);
        $result = ApiCalls::CurlPost($data, $url);
        $result = json_decode($result, true);

        $data = [
            'page_title' => 'User Edit'
        ];

        if (request()->expectsJson()) {
            return response()->json($result);
        }
        return view('users.edit', $data);
    }
    public function show($id){
        $url = "user_mgt/get_user_by_user_id.php";

        $data = json_encode([
            'user_id' => $id,
            'api_token' => env('LUPMISAPIKEY')// make the API token a constant
        ]);
        $result = ApiCalls::CurlPost($data, $url);
        $result = json_decode($result, true);
        if (request()->expectsJson()) {
            return response()->json($result);
        }

        $data = [
            'page_title' => 'User Profile',
            'user' => $result
        ];
        return view('admin.user-show', $data);
    }
    public function getprofile_json(){
        $user_id = session('current_user.user_id');
        $url = "user_mgt/get_user_by_user_id.php";
        // dd($user_id);
        $data = json_encode([
            'user_id' => $user_id,
            'api_token' => env('LUPMISAPIKEY')// make the API token a constant
        ]);
        $result = ApiCalls::CurlPost($data, $url);
        $result = json_decode($result, true);
        if ($result['success'] == true) {
            // code...
            return response()->json(['code' => 1, 'user_details' => $result['data']]);
        }
        else{
            return response()->json(['code' => 3, 'msg' => 'Your request could not be handled at this time']);
        }
    
        
    }
 
    public function store(Request $request){
        $url = "user_mgt/add_usr_user.php";

        $this->validate($request, [
            'full_name'   => 'required|string|max:255',
            'username'    => 'required|string|max:255|unique:users,username',
            'ua_position' => 'required|string',
            // 'allowed_apps'=> 'required|array',
            'user_status'      => 'required|string',
            'gender'      => 'required|in:male,female',
            'district_id'   => [
                Rule::requiredIf(function () use ($request) {
                    return in_array($request->user_type, ['district_user']);
                }),
                'integer'
            ],
            'region_id'   => [
                Rule::requiredIf(function () use ($request) {
                    return in_array($request->user_type, ['regional_luspa', 'national_luspa']);
                }),
                'integer'
            ],
            'user_type'   => 'required|string',
            'email'       => 'required|email|unique:users,email',
            'phone'       => ['required', new GhanaPhoneRule],
        ], [
            'full_name.required'   => 'Please provide the full name.',
            'username.required'    => 'A username is required.',
            'username.unique'      => 'This username is already taken.',
            'ua_position.required' => 'Position is mandatory.',
            // 'allowed_apps.required'=> 'Select at least one application.',
            'gender.required'      => 'Gender is required.',
            'district_id.required' => 'District must be selected.',
            'region_id.required'   => 'Region is required',
            'user_type.required'   => 'User type is required.',
            'email.required'       => 'Email address is required.',
            'email.email'          => 'Please enter a valid email address.',
            'user_status.required'      => 'Please select user status.',
            'email.unique'         => 'This email is already registered.',
            'phone.required'       => 'Phone number is required.',
        ]);

        // dd($request->ua_position);
        $password = Str::random(10);
        $user_group_matrix = Config('usergroupmatrix'); 
        //$allowed_apps_all = $user_group_matrix[ucwords($request->ua_position)];
        $allowed_apps_all = collect($user_group_matrix)
                            ->filter(
                                fn (array $user_group_matrix, string $groupName) =>
                                    str_contains(strtolower($groupName), strtolower($request->ua_position))
                            )->all();

        $allowed_apps = collect($allowed_apps_all)
                        ->filter(fn ($allowed) => $allowed === true)
                        ->keys()
                        ->values()
                        ->all();
        
        $data = json_encode([
            'full_name' => $request['full_name'],
            'username' => $request['username'],
            'ua_position' => $request['ua_position'],
            'email' => $request['email'],
            'title' => $request['title'], 
            'allowed_apps' => implode(", ", $allowed_apps), 
            'is_password_changed' => false,
            'password_hint' => 'none', 
            'phone' => str_replace('+', '',$request['phone']), 
            'gender' => $request['gender'],
            'user_type' => $request['user_type'],
            'pass' => $password,
            'is_disabled' => false,
            'region_id' => $request['region_id'],
            'district_id' => $request['district_id'], 
            'api_token' => env('LUPMISAPIKEY'),
        ]);

        
        // dd($data);
        //todo determine the allowed_apps user
        //user_type and ua_position
        if ($request->user_type == 'district_user') {
            // code...
        }
        elseif ($request->user_type == 'regional_luspa') {
            // code...
        }
        elseif ($request->user_type == 'national_luspa') {
            // code...
        }
        /*
        'permit_tools_backend',
        'update_permits',
        'drawing_tools',
        'view_drawing_tools',
        'admin_gui',
    
        */
        // "drawing-tools"
        // "permit-tools"
        // "admin-gui"
        // ""

        $result = ApiCalls::CurlPost($data, $url);
        $result = json_decode($result, true);

        if ($result['success'] == false) {
            return response()->json($result);
        }

        \Log::info("Your Password is $password");
        if(env('APP_ENV') == 'production'){
            Mail::to($request->email)->send(new UserAccountsMail($password, $request->username));
        }
        $sms_message = "Hello {$request->full_name}, your LUPMIS account has been successfully created\n";
        $sms_message .= "Username: {$request->username}\n";
        $sms_message .= "Password: $password\n";
        $sms_message .= "Login URL: https://lupmis4luspa.org"; 

        $sms_data = [
            'recipient' => $request['phone'],
            'message' => $sms_message
        ];
        if(env('APP_ENV') == 'production'){
            $sms = new SmsLibrary;
            $retval = $sms->SendMnotitySms($sms_data);
        }
        \Log::info("SMS Body : $sms_message");

        if ($request->expectsJson()) {
            return response()->json($result);
        }
    }

    public function update(Request $request){
        
        $url = "user_mgt/update_usr_user.php";
        $userId = $request->input('user_id');        
        $this->validate($request, [
            'full_name'   => 'required|string|max:255',
            'username'    => 'required|string|max:20|',
            'ua_position' => 'required|string',
            // 'allowed_apps'=> 'required|array',
            'user_status' => 'required|string',
            'district_id' => 'required|integer',
            'region_id' => 'sometimes|integer',
            'gender'      => 'required|in:male,female',
            /*
            'district_id'   => [
                Rule::requiredIf(function () use ($request) {
                    return in_array($request->user_type, ['district_user']);
                }),
                'integer'
            ],
            'region_id'   => [
                Rule::requiredIf(function () use ($request) {
                    return in_array($request->user_type, ['regional_luspa', 'national_luspa']);
                }),
                'integer'
            ],
            */
            'user_type'   => 'required|string',
            'email'       => 'required|email|unique:users,email',
            'phone'       => ['required', new GhanaPhoneRule],
        ], [
            'full_name.required'   => 'Please provide the full name.',
            'username.required'    => 'A username is required.',
            'ua_position.required' => 'Position is mandatory.',
            // 'allowed_apps.required'=> 'Select at least one application.',
            'gender.required'      => 'Gender is required.',
            'district_id.required' => 'District must be selected.',
            'region_id.required'   => 'Region is required',
            'user_type.required'   => 'User type is required.',
            'user_status.required' => 'Please select user status.',
            'email.required'       => 'Email address is required.',
            'email.email'          => 'Please enter a valid email address.',
            'email.unique'         => 'This email is already registered.',
            'phone.required'       => 'Phone number is required.',
        ]);
        $is_disabled = ($request->user_status == 'active') ? 'false' : 'true';
        $user_group_matrix = Config('usergroupmatrix'); 
        //$allowed_apps_all = $user_group_matrix[ucwords($request->ua_position)];
        $allowed_apps_all = collect($user_group_matrix)
                            ->filter(
                                fn (array $user_group_matrix, string $groupName) =>
                                    str_contains(strtolower($groupName), strtolower($request->ua_position))
                            )->all();

        $allowed_apps = collect($allowed_apps_all)
                        ->filter(fn ($allowed) => $allowed === true)
                        ->keys()
                        ->values()
                        ->all();

        $userData = [
            'user_id'      => $request->user_id,
            'full_name'    => $request->full_name,
            'username'     => $request->username,
            'ua_position'  => $request->ua_position,
            'email'        => $request->email,
            'title'        => $request->title,
            // 'allowed_apps' => implode(", ", $request->allowed_apps), 
            'allowed_apps' => implode(", ", $allowed_apps), 
            'phone'        => str_replace('+', '', $request->phone),

            'gender'       => $request->gender,
            'user_type'    => $request->user_type,
            'is_disabled' => $is_disabled,
            'district_id' => $request->district_id, 
            'region_id'   => $request->region_id, 
            'api_token' => config('services.lupmis.api_key'), //env('LUPMISAPIKEY'),
        ];
        
        
        if ($request->has('expire_password')) {
            #$user_data['is_password_changed'] = 'YES';
            #$reset_link = env('APP_URL') . "/reset-auth/" . $request->user_id;
            #Mail::to($recipientEmail)->send(new PasswordResetMail($request->fullname, $reset_link));
        }
        if (config('app.env') === 'local' && $request->filled('reset_password')) {
            $reset_url = "user_mgt/reset_user_password.php";
            $reset_data["api_token"] = config('services.lupmis.api_key');
            $reset_data['user_id'] = $request->user_id; 
            $reset_data['pass'] = $request->reset_password;
            $data = json_encode($reset_data);
            $retval = ApiCalls::CurlPost($data, $reset_url);
            $retval = json_decode($retval, true);
        }
       
        $result = ApiCalls::CurlPost(json_encode($userData), $url);
        $decodedResult = json_decode($result, true);
 
        return response()->json($decodedResult ?? ['error' => 'Invalid API Response']);
    }

    
    public function profileupdate(Request $request){
        $url = "user_mgt/update_usr_user.php";
     
        $user_data = [
            'full_name' => $request['full_name'],
            'username' => $request['username'],
            'user_id' => $request['user_id'],
            'email' => $request['email'],
            'phone' => $request['phone'], 
            'gender' => $request['gender'],
            'api_token' => env('LUPMISAPIKEY'),
        ];
        if ($request->filled('password')) {
            $user_data['password'] = $request->password;
            $reset_url = "user_mgt/reset_user_password.php";
            $reset_data["api_token"] = env('LUPMISAPIKEY');
            $reset_data['user_id'] = $request->user_id; 
            $reset_data['pass'] = $request->password;
            $data = json_encode($reset_data);
            $retval = ApiCalls::CurlPost($reset_data, $reset_url);
            $retval = json_decode($retval, true);
        }

        $data = json_encode($user_data);
        $result = ApiCalls::CurlPost($data, $url);
        $result = json_decode($result, true);
        if (request()->expectsJson()) {
            return response()->json($result);
        }
    }
    public function getPositionsMap()
    {
        $district_groups = array_keys(Config('usergroupmatrix'));
        $map = [
            'district_user' => $district_groups,
            /*
            'district_user' => [
                "PPD Head", "Works Head", "MIS", "PPD Staff", "Works Staff", 
                "Devt Planning Officer", "MCE", "DCE", "Urban Roads Department Head",
                "District Fire Officer", "District Disaster Prevention Department",
                "Head of District Health Department", "Representative of the Lands Commission",
                "Representative of the Environmental Protection Agency", "Rep from Traditional Council",
                "Chairman of the Works Sub Committee", "Chairman of Development Sub Planning Committee",
                "Nominated Elected Assembly Memebers"
            ],
            */
            'national_luspa' => ["Director", "IT Head", "Staff"],
            'regional_luspa' => ["Director", "Staff"]
        ];

        return response()->json([
            'success' => true,
            'data' => $map
        ]);
    }
}
