<?php

namespace App\Http\Controllers\Accounts;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Gender;
use App\Models\AccountTitle;

class AccountTitlesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:account-title-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        if (!$this->modulePermissionCheck('ACCOUNT_TITLE')) {
            abort(404);
        }

        $data = AccountTitle::select([
                'account_titles.*',
                'genders.name as gender',
            ])
            ->leftjoin('genders', 'genders.id', 'account_titles.gender_id');

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

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->orWhere('account_titles.name', 'like', '%'.$search_query.'%')
                        ->orWhere('account_titles.value', 'like', '%'.$search_query.'%')
                        ->orWhere('genders.name', 'like', '%'.$search_query.'%');
                })
                ->paginate($sort_by);

            return view('account-titles.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('account-titles.index',compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = AccountTitle::max('priority');
        $priority = $priority != '' ? $priority : 0;
        $genders = Gender::select(['id','name'])->get();

        return view('account-titles.create', compact('genders','priority'));
    }

    /**
     * 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|unique:account_titles',
            'value'     => 'required',
            'gender_id' => 'required',
            'priority'  => 'required'
        ]);

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

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $data = AccountTitle::create($data);

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

    /**
     * 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)
    {
        $genders = Gender::select(['id','name'])->get();
        $account_title = AccountTitle::find($id);

        return view('account-titles.edit', compact('account_title', 'genders'));
    }

    /**
     * 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|unique:account_titles,name,'.$id,
            'value'     => 'required',
            'gender_id' => 'required',
            'priority'  => 'required'
        ]);

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

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $account_title = AccountTitle::find($id);

        if (!$account_title) {
            return redirect()->route('account-titles.index')
                ->with('error','Account Title not found!');
        }

        $account_title->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Account Title updated successfully.',
            ]);
        }

        return redirect()->route('account-titles.index')
            ->with('success','Account Title updated successfully');
    }

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

        $Redirect = 'account-titles';

        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 = AccountTitle::where('id', '=', $request->id)->update($data);

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