<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\User;
use App\Models\TestDeptPermission;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Maatwebsite\Excel\Facades\Excel;
use Session;
use App\Imports\ImportDepartment;
use App\Exports\ExportDepartmentFormat;
use Yajra\DataTables\Facades\DataTables;

class DepartmentsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:department-list', ['only' => ['index']]);
    }

    public function index(Request $request)
    {
        $data = Department::select([
                    'test_departments.id',
                    'test_departments.name',
                    // 'test_departments.code',
                    // 'test_departments.description',
                    'test_departments.priority',
                    'test_departments.page_break',
                    'test_departments.show_in_report',
                    'test_departments.show_report_heading',
                    'test_departments.status',
                ])
                // ->orderBy('test_departments.name', 'ASC')
                ->orderBy('priority','ASC');

        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('test_departments.name', 'like', '%'.$search_query.'%')
                    ->orWhere('test_departments.description', 'like', '%'.$search_query.'%');
            })

            ->paginate($sort_by);

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

            return view('departments.index', compact('data'));
        }
    }

    public function create()
    {
        $priority = Department::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('departments.create',compact('priority'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:test_departments,name,NULL,id,deleted_at,NULL',
        ]);

        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'
        ]);

        $department = Department::create($data);

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

    public function edit($id)
    {
        $data = Department::find($id);

        return view('departments.edit',compact('data'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:test_departments,name,'.$id.',id,deleted_at,NULL',
        ]);

        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'
        ]);

        $department = Department::find($id);

        if (!$department) {
            return redirect()->back()
                ->with('error','Test Departmrnt not found!');
        }

        $department->update($data);

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

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

            $Redirect = 'departments';

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

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

            $Redirect = 'departments';

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Show Report Heading status successfully change'],
                    'data'    => [
                        'redirect' => $Redirect,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data'    => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function showReport(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('show_in_report' => $request->status );
            $Update = Department::where('id', '=', $request->id)->update($data);

            $Redirect = 'departments';

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

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

            $Redirect = 'departments';

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

    public function destroy(Request $request)
    {
        Department::find($request->id)->delete();

        $Redirect = 'departments';

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

    public function importCreate()
    {
       return view('departments.import');
    }

    public function importPreview(Request $request)
    {
        $department_data = [];

        Session::put('DepartmentData', $department_data);

        try {
            Excel::import(new ImportDepartment, $request->file('departments'));

            $data = Session::get('DepartmentData');

            return view('departments.preview', compact('data'));

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => [$e->getMessage()],
            ]);
        }
    }

    public function importSessionDestroy(Request $request)
    {
        $department_data = Session::get('DepartmentData');

        unset($department_data[$request->id]);

        Session::put('DepartmentData', $department_data);

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

    public function importStore(Request $request)
    {
        $data = Session::get('DepartmentData');

        if($data){

            foreach ($data as $row){

                $departments = ([
                    'name'        => $row[0],
                    'description' => $row[1],
                    'page_break'  => ($row[2] == 'Yes') ? '1' : '0',
                    'status'      => ($row[3] == 'Inactive') ? '0' : '1',
                ]);

                $exist_departments = Department::where('name', $row[0])->exists();

                if(!$exist_departments){
                    Department::create($departments);
                }
            }

            return redirect()->route('departments.index')
                ->with('success','Departments uploaded successfully');
        }else{
           return redirect()->back()
                ->with('error','Empty file uploaded');
        }
    }

    public function exportFormat()
    {
        return Excel::download(new ExportDepartmentFormat, 'department-format.xlsx');
    }

    public function permission(Request $request)
    {
        $data = User::select(['id', 'name'])->where('is_super_admin', 0)->where('status', 1);

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

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

            return view('departments.permission', compact('data'));
        }
    }

    public function permissionEdit(Request $request, $id)
    {
        if ($id != '') {
            $user = User::select(['id', 'name'])->where('id', $id)->first();

            $data = Department::select([
                'test_departments.id',
                'test_departments.name',
                'test_dept_permissions.permission',
            ])
            ->leftjoin('test_dept_permissions', function($query) use ($id) {
                $query->on('test_dept_permissions.test_departments_id', 'test_departments.id')
                ->where('test_dept_permissions.user_id','=', $id);
            })
            ->where('test_departments.status', 1)
            ->where('test_departments.deleted_at', null)
            ->orderBy('test_departments.id', 'ASC');

            if ($request->ajax()) {
                $search_query = $request->get('query');

                $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('test_departments.name', 'like', '%'.$search_query.'%');
                })
                ->get();

                return view('departments.permission-edit-table', compact('data', 'user'));
            }
            else
            {
                $data = $data->get();

                return view('departments.permission-edit', compact('data', 'user'));
            }
        }
    }

    public function permissionUpdate(Request $request, $id)
    {
        $data = $request->except([
            '_token',
            '_method'
        ]);

        if ($data['id'] == 'all') {

            $dept = Department::select([
                'test_departments.id',
                'test_departments.name',
            ])
            ->where('test_departments.status', 1)
            ->where('test_departments.deleted_at', null)
            ->get();

            foreach ($dept as $key => $value) {
                if($data['status'] == 1) {
                    $test_dept_permissions = ([
                        'user_id'             => $id,
                        'test_departments_id' => $value->id,
                        'permission'          => 1,
                    ]);

                    TestDeptPermission::updateOrCreate($test_dept_permissions);
                } else {
                    TestDeptPermission::where('user_id', $id)->where('test_departments_id', $value->id)->delete();
                }
            }
        } else {
            if($data['status'] == 1) {
                $test_dept_permissions = ([
                    'user_id'             => $id,
                    'test_departments_id' => $data['id'],
                    'permission'          => 1,
                ]);

                TestDeptPermission::updateOrCreate($test_dept_permissions);
            } else {
                TestDeptPermission::where('user_id', $id)->where('test_departments_id', $data['id'])->delete();
            }
        }

        return response()->json([
            'success' => true,
            'message' => 'Permissions Updated successfully'
        ]);
    }
}
