<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Representative;
use App\BloodTypes\BloodTypes;
use Throwable;
use App\Exceptions\GlobalException;
use App\Models\RelationShip;
use App\Helper\Helper;


class RepresentativeController extends Controller
{
    /**
     * 
     */
    public function create(Request $request,BloodTypes $bloodTypes){
       try{
        $representative = new Representative();
        if(!($request->method() === "POST")){
            $patientId = $request->all()["patientId"];
            return view("create-representative",[
                "patientId"=>$patientId,
                "representative"=>$representative,
                "bloodTypes"=>$bloodTypes->getTypes()
            ]);
        }
        $data = $request->all();
        $model = $representative->createModelFromRequest($data);
        $representative = $representative->create($model);

        $relationship = RelationShip::getDataFromModel($representative->id,$data);
        $relationship = RelationShip::create($relationship);

        $dataAppointment = [];
        

        if(isset($data["continueFromAppointment"]) && ($data["continueFromAppointment"] === "1")){
            Helper::fillDataFromAppointment($data, $dataAppointment);
            return redirect()->route("/admin/create-appointment",array_merge(
                [
                    "patientId"=>$data["patient_id"]
                ],
                $dataAppointment
            ));
        }
          
        return redirect()->route("/admin/detail-patient",
        [
            "id"=>$data["patient_id"]
        ]);

       }catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }

    /**
     * 
     */
    public function createFromPatient(Request $request,BloodTypes $bloodTypes){
       try{
        $representative = new Representative();
        $patientId = $request->all()["patient"]["id"];
        return view("create-representative",[
            "patientId"=>$patientId,
            "representative"=>$representative,
            "bloodTypes"=>$bloodTypes->getTypes()
        ]); 
       }catch (Throwable $th) {
        throw new GlobalException($th->getMessage());
    }
    }
}
