<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Account;
use App\Models\AccountingGroup;
use App\Models\Company;
use App\Models\CompanyAddress;
use App\Models\User;
use App\Models\UserType;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
use Illuminate\Contracts\Session\Session;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Auth;
use Yajra\DataTables\DataTables;

class UserController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:users-list|users-create|users-edit|users-delete', ['only' => ['index', 'store']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $company_id      = \Auth::user()->company_id ?? '';
        $company_address = \Session::get('company_data');
        $countryCode     = $company_address['country_code'] ?? 'us';
        $Userdata        = User::where('is_super_admin', 0)->with('getComapnyDetails');
        // $Userdetails     = User::where('is_super_admin', 0)->with('getComapnyDetails')->get();

        $user_types = UserType::select('id', 'code', 'name')->get();

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');
            $role         = $request->get('role');

            $Userdata = $Userdata->when(!empty($search_query), function ($query) use ($search_query) {
                        return $query->where('name', 'like', '%'.$search_query.'%');
                    })
                    ->when(!empty($role), function ($query) use ($role) {
                        return $query->role($role);
                    })
                    ->paginate($sort_by);

            return view('users.table', compact('Userdata','countryCode' , 'user_types'));
        }
        else
        {
            $Userdata = $Userdata->paginate(10);
            $roles    = Role::pluck('name', 'name')->all();

            return view('users.index', compact('Userdata','countryCode','roles' , 'user_types'));
        }
    }

    public function list(Request $request)
    {

    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $company_id      = Auth::user()->company_id ?? '';
        $company_address = \Session::get('company_data');
        $countryCode     = $company_address['country_code'] ?? 'us';
        $roles           = Role::pluck('name', 'name')->all();
        $company         = Company::get();
        $preparedBy      = User::select('id','name','email')->where('status',1)->get();
        $account = Account::select('id', 'name')
            ->whereIn('accounting_group_id', function ($query) {
                $query->select('id')
                    ->from('accounting_groups')
                    ->where('code', 'SUNDRY_CREDITORS')
                    ->orWhere('code', 'SUNDRY_DEBTORS');
            })
            ->where('status', 1)
            ->get();
        $user_types = UserType::select('id', 'code', 'name')->get();

        return view('users.create', compact('roles', 'countryCode','company','preparedBy','account','user_types'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name'        => 'required',
            'email'       => 'required|email|unique:users,email',
            'username'    => 'required|unique:users,username',
            'password'    => 'required|same:confirm-password|min:8',
            'roles'       => 'required',
            'prepared_by' => 'required',
            'phone_no'    => 'max:16',

        ]);
        $customMessages = [
            'username.unique' => 'The User ID is already taken.',
        ];

        $validator->setCustomMessages($customMessages);

        if ($validator->fails())         {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data' => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }


        $input                   = $request->all();
        $input['phone_no']       = $this->cleanAndValidateContactNumbers($request->phone_no);
        $input['whatsapp_no']    = $this->cleanAndValidateContactNumbers($request->whatsapp_no);
        $input['password']       = Hash::make($input['password']);

        $path_signature          = "/user_signature";
        $input['user_signature'] = '';

        if ($request->hasFile('user_signature')) {
            $response      = uploadImage($path_signature, $request->user_signature);

            if ($response['status'] == true) {
                $input['user_signature'] = $response['file_name'];
            }
        }

        $path_userImage = "/user_signature";
        $input['user_image'] = '';

        if ($request->hasFile('user_image')) {
            $response      = uploadImage($path_userImage, $request->user_image);

            if ($response['status'] == true) {
                $input['user_image'] = $response['file_name'];
            }
        }

        $user = User::create($input);
        $user->assignRole($request->input('roles'));

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'User created successfully',
                'data' => $user
            ]);
        }
        return redirect()->route('users.index')
            ->with('success', 'User created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $user = User::find($id);
        return view('users.show', compact('user'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user       = User::find($id);
        $roles      = Role::pluck('name', 'name')->all();
        $company    = Company::get();
        $userRole   = $user->roles->pluck('name', 'name')->all();
        $preparedBy = User::select('id','name','email')->where('status',1)->get();
        $user_types = UserType::select('id', 'code', 'name')->get();

        return view('users.edit', compact('user', 'roles', 'userRole', 'company','preparedBy','user_types'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name'     => 'required',
            'email'    => 'required|email|unique:users,email,' . $id,
            'password' => 'same:confirm-password',
            'username' => 'required|unique:users,username,' . $id,
            'roles'    => 'required'
        ]);
        $customMessages = [
            'username.unique' => 'The User ID is already taken.',
        ];

        $validator->setCustomMessages($customMessages);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                            'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data' => []
                ]);
            }
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $input = $request->all();

        if (!empty($input['password'])) {
            $input['password'] = Hash::make($input['password']);
        } else {
            $input = Arr::except($input, array('password'));
        }

        $user = User::find($id);

        if ($request->hasFile('user_signature')) {
            $path     = "user_signature";
            $response = uploadImage($path,$request->user_signature);

            if ($response['status'] == true) {
                $input['user_signature'] = $response['file_name'];
            }
        }

        $path_userImage = "user_image";

        if ($request->hasFile('user_image')) {
            $input['user_image'] = '';
            $response      = uploadImage($path_userImage, $request->user_image);

            if ($response['status'] == true) {
                $input['user_image'] = $response['file_name'];
            }
        }

        $user->update($input);
        DB::table('model_has_roles')->where('model_id', $id)->delete();

        $user->assignRole($request->input('roles'));

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'User updated successfully',
                'data' => $user
            ]);
        }
        return redirect()->route('users.index')
            ->with('success', 'User updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        User::find($request->id)->delete();
        $Redirect = 'users';

        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }


    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data = array('status' => $request->status);
            $Update = User::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['User status successfully change'],
                    'data' => [
                        'redirect' => '/users/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function submitUserFinancialYear(Request $request)
    {
        if ($request->ajax()) {
            $financialyear = $request->financialyear ?? '';

            $data   = array('my_financial_year_id' => $financialyear);
            $Update = User::where('id', '=', \Auth()->id())->update($data);
            $user   = \Auth::user();
            $user->my_financial_year_id = $financialyear;
            $user->save();

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['User financial year successfully updated'],
                    'data' => [
                        'redirect' => '/users/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function searchAccounts(Request $request)
    {
        $searchTerm = $request->search_text;

        $accountsQuery = Account::select('id', 'name')
            ->whereIn('accounting_group_id', function ($query) {
                $query->select('id')
                    ->from('accounting_groups')
                    ->where('code', 'SUNDRY_CREDITORS')
                    ->orWhere('code', 'SUNDRY_DEBTORS');
            })
            ->where('status', 1);

        if ($searchTerm) {
            $accountsQuery->where('name', 'LIKE', '%' . $searchTerm . '%');
        }

        $results = $accountsQuery->get();

        return response()->json(['result' => $results, 'status' => true]);
    }



    public function changeUserType(Request $request)
    {
        if ($request->ajax()) {
            $userId   = $request->id;
            $userType = $request->user_type;

            $user = User::find($userId);

            if ($user) {
                $user->user_type = $userType;
                $user->save();

                return response()->json([
                    'success' => true,
                    'message' => 'User Type successfully updated',
                    'data'    => [ 
                    ]
                ]);
            }

            return response()->json([
                'success' => false,
                'message' => 'User not found',
            ]);
        }
    }



}
