<?php

namespace App\Http\Controllers\Settings;

use App\Http\Controllers\Controller;
use App\Models\OrganizationDepartment;
use Illuminate\Http\Request;

class OrganizationDepartmentController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:organization-department-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = OrganizationDepartment::select([
                'organization_departments.id',
                'organization_departments.name',
                'organization_departments.code',
                'organization_departments.details',
                'organization_departments.priority',
                'organization_departments.status',
                'organization_departments.is_default',
            ]);

        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->where('organization_departments.name', 'like', '%' . $search_query . '%');
                })
                ->paginate($sort_by);

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

            return view('organization-department.index', compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = OrganizationDepartment::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('organization-department.create', compact('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:organization_departments',
        ]);

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

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

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

        // $data['company_id'] = \Auth::user()->company_id;

        $source = OrganizationDepartment::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Organization Department Created successfully',
                'data' => $source
            ]);
        }
        return redirect()->route('organization-department.index')
            ->with('success', 'Organization Department 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)
    {
        $dept = OrganizationDepartment::find($id);

        return view('organization-department.edit', compact('dept'));
    }

    /**
     * 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:organization_departments,name,' . $id,
        ]);

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

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

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

        $source = OrganizationDepartment::find($id);

        if (!$source) {
            return redirect()->route('organization-department.index')
                ->with('error', 'Organization Department not found!');
        }

        $source->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Organization Department updated successfully',
                'data' => $source
            ]);
        }

        return redirect()->route('organization-department.index')
            ->with('success', 'Organization Department updated successfully');
    }


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

        $Redirect = 'organization-department';

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

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