<?php

namespace App\Http\Controllers\IpdAdmission;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\IpdDetail;
use App\Models\SymptomClassification;
use App\Models\Symptom;
use App\Models\BedGroup;
use App\Models\Bed;
use App\Models\PaymentTerm;
use App\Models\Account;
use App\Models\EnquirySource;
use App\Models\MasterType;

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

    public function index(Request $request)
    {
        $data = IpdDetail::select([
                    'ipd_details.id',
                    'ipd_details.case_no',
                    'ipd_details.previous_medical_issue',
                    'ipd_details.credit_limit',
                    'accounts.name as patient_name',
                    'consultants.name as consultant_name',
                    'beds.name as bed_no',
                    'account_contacts.phone_no',
                ])
                ->leftjoin('accounts', 'accounts.id', 'ipd_details.patient_id')
                ->leftjoin('accounts as consultants', 'consultants.id', 'ipd_details.doctor_id')
                ->leftjoin('beds', 'beds.id', 'ipd_details.bed_no_id')
                ->leftjoin('account_contacts', 'account_contacts.id', 'ipd_details.patient_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->where('ipd_details.height', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

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

            return view('ipd-details.index', compact('data'));
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $symptom_types = SymptomClassification::select('id', 'symptoms_type')->where('status', 1)->get();
        $bed_groups    = BedGroup::select('id', 'name')->get();
        $bed_numbers   = Bed::select('id', 'name')->get();
        $payment_terms = PaymentTerm::select('id', 'payment_term_name')->get();

        $sources       = EnquirySource::select('id', 'enquiry_source_name')->get();
        $account_types = MasterType::select('id', 'type_name')->where('type_name', 'TPA - (Third Party Administrator)')->get();

        return view('ipd-details.create', compact('symptom_types', 'bed_groups', 'bed_numbers', 'payment_terms', 'sources', 'account_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(), [
            'patient_id'     => 'required|unique:ipd_details,patient_id,NULL,id',
            'doctor_id'      => 'required',
            'admission_date' => 'required',
            'credit_limit'   => 'required',
            'bed_no_id'      => 'required',
        ]);

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

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

        $data['admission_date'] = $request->admission_date != '' ? date('Y-m-d', strtotime($request->admission_date)) : '';

        $company_id = auth()->user()->company_id;

        $data['company_id'] = $company_id;

        IpdDetail::create($data);

        return redirect()->route('ipd-details.index')->with('success','Admission was 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)
    {
        $symptom_types = SymptomClassification::select('id', 'symptoms_type')->where('status', 1)->get();
        $bed_groups    = BedGroup::select('id', 'name')->get();
        $bed_numbers   = Bed::select('id', 'name')->get();
        $payment_terms = PaymentTerm::select('id', 'payment_term_name')->get();
        $data          = IpdDetail::find($id);

        $patient    = Account::select('name')->where('id', $data->patient_id)->first();
        $consultant = Account::select('name')->where('id', $data->doctor_id)->first();

        return view('ipd-details.edit', compact('symptom_types', 'bed_groups', 'bed_numbers', 'payment_terms', 'data', 'consultant', 'patient'));
    }

    /**
     * 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(), [
            'patient_id'     => 'required|unique:ipd_details,patient_id,'.$id.',id',
            'doctor_id'      => 'required',
            'admission_date' => 'required',
            'credit_limit'   => 'required',
            'bed_no_id'      => 'required',
        ]);

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

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

        $ipd_detail = IpdDetail::find($id);

        $data['admission_date'] = $request->admission_date != '' ? date('Y-m-d', strtotime($request->admission_date)) : '';

        $ipd_detail->update($data);

        return redirect()->route('ipd-details.index')->with('success','Admission was updated successfully');
    }

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

        $Redirect = 'ipd-details';

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

    public function getSymptomsTitle(Request $request)
    {
        $symptom_type_id = $request->symptom_type;

        if ($symptom_type_id) {

            $symptoms = Symptom::select('id', 'symptoms_title')
                ->where('type', $symptom_type_id)
                ->where('status', 1)
                ->get();

            $data = '';

            foreach ($symptoms as $symptom) {
                $data .= '<option value="'. $symptom->id .'">'. $symptom->symptoms_title .'</option>';
            }

            return response()->json([
                'success' => true,
                'data'    => $data
            ]);
        } else {
            return response()->json([
                'success' => true,
                'data'    => '',
            ]);
        }
    }

    public function getSymptomsDescription(Request $request)
    {
        $symptom_id = $request->symptom_title;

        if ($symptom_id) {

            $symptoms = Symptom::select('description')
                ->where('id', $symptom_id)
                ->where('status', 1)
                ->first();

            return response()->json([
                'success' => true,
                'data'    => $symptoms->description,
            ]);
        } else {
            return response()->json([
                'success' => true,
                'data'    => '',
            ]);
        }
    }
}
