<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use App\Models\Department;
use App\Models\SignaturePermission;
use App\Models\Signature;
use App\Models\TestUnit;
use App\Models\TestItem;
use App\Models\TestItemNormalRange;
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 App\Imports\ImportTestUnit;
use App\Exports\ExportTestUnitFormat;
use Session;

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

    public function index(Request $request)
    {
        $data = Signature::select([
                    'signatures.id',
                    'signatures.name',
                    'signatures.signature_for',
                    'signatures.signature',
                    'signatures.priority',
                    'signatures.is_default',
                    'signatures.status',
                ]);

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

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

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

    public function create()
    {
        return view('signatures.create');
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:signatures,name,NULL,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'
        ]);

        if ($request->hasFile('signature')) {

            $path = "signature";
            $response = uploadImage($path,$request->signature);

            if ($response['status'] == true) {

                $signature = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }

            $data['signature'] = $signature;
        }

        $max_priority = Signature::max('priority');
        $priority = ($max_priority ?? 0) + 1;

        $data['priority'] = $priority;

        $default_check = Signature::where(['is_default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['is_default'] = 1;
        }

        $signature = Signature::create($data);

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

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

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

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:signatures,name,'.$id.',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',
            'signature'
        ]);

        $signature = Signature::find($id);

        if ($request->hasFile('signature')) {

            $old_image = $signature->signature;

            $path     = "signature";
            $response = uploadImage($path,$request->signature,$old_image);

            if ($response['status'] == true) {

                $signature_file_path = $response['file_name'];
            } else {
                if ($request->ajax()) {
                    return response()->json([
                        'success' => false,
                        'message' => $response['message'],
                        'data'    => []
                    ]);
                }
                return redirect()->back()->with('error', $response['message']);
            }

            $data['signature'] = $signature_file_path;
        }

        if (!$signature) {
            return redirect()->route('signatures.index')
                ->with('error','Signature not found!');
        }

        $signature->update($data);

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

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

            $Redirect = 'signatures';

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

    public function isDefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $count  = Signature::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default signature!'],
                    'data'    => []
                ]);
            } else {
                $Update = Signature::where('id', '=', $request->id)->update($data);

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

    public function destroy(Request $request)
    {
        $signature = Signature::find($request->id);

        $old_image = $signature->signature;

        if ($old_image != '') {
            deleteImage($old_image);
        }

        $signature->delete();

        $Redirect = 'signatures';

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

    public function permission(Request $request)
    {
        $data = Signature::select(['id', 'name', 'signature_for'])->where('status', 1)->withCount('permissions');

        $totalDept = Department::where('status', 1)->count();

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

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

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

    public function permissionEdit(Request $request, $id)
    {
        if ($id != '') {
            $signature     = Signature::select(['id', 'name', 'signature_for'])->where('id', $id)->first();
            $depart_ids = $this->aleradyAssignedDeparts($id);

            $data = Department::select([
                'test_departments.id',
                'test_departments.name',
                'signature_permissions.permission',
            ])
            ->leftjoin('signature_permissions', function($query) use ($id) {
                $query->on('signature_permissions.test_departments_id', 'test_departments.id')
                ->where('signature_permissions.signatures_id','=', $id);
            })
            ->where('test_departments.status', 1)
            ->whereNotIn('test_departments.id', $depart_ids)
            ->orderBy('test_departments.name', '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('signatures.permission-edit-table', compact('data', 'signature','id'));
            }
            else
            {
                $data = $data->get();

                return view('signatures.permission-edit', compact('data', 'signature','id'));
            }
        }
    }

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

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

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

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

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

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

        return response()->json([
            'success' => true,
            'message' => 'Permissions Updated successfully'
        ]);
    }
    public function aleradyAssignedDeparts($id)
    {
        $signature     = Signature::select(['signature_for'])->where('id', $id)->first();
        $type          = $signature->signature_for;
        $signature_ids = Signature::select(['id'])
            ->where('signature_for', $type)
            ->whereNot('id', $id)
            ->get()
            ->pluck('id')
            ->toArray();

        $depart_ids = Department::select('test_departments.id')
            ->leftjoin('signature_permissions', function($query) use ($signature_ids) {
                $query->on('signature_permissions.test_departments_id', 'test_departments.id')
                ->whereIn('signature_permissions.signatures_id', $signature_ids);
            })
            ->whereNotNull('signature_permissions.id')
            ->get()
            ->pluck('id')->toArray();

        return $depart_ids;
    }
}
