<?php

namespace App\Services\MedicalHealth;

use App\Services\AapaleSarkarLoginCheckService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use App\Models\MedicalHealth\RenewalNursingLicense;
use App\Models\ServiceCredential;
use App\Models\Status;
use App\Services\CommonService;

class RenewalNursingLicenseService
{
    protected $aapaleSarkarLoginCheckService;
    protected $commonservice;

    public function __construct(AapaleSarkarLoginCheckService $aapaleSarkarLoginCheckService , CommonService $commonservice)
    {
        $this->aapaleSarkarLoginCheckService = $aapaleSarkarLoginCheckService;
        $this->commonservice = $commonservice;
    }


    public function store($request)
    {
        $user = Auth::user();
        $request['user_id'] = Auth::user()->id;
        $request['service_id'] = "2025";

        if ($request->hasFile('prescribed_formats')) {
            $request['prescribed_format'] = $request->prescribed_formats->store('health-department/renew-nursing-license', 'public');
        }
        $renewNursingLicense=RenewalNursingLicense::create($request->except('application_no'));
         if($renewNursingLicense){

             $applicationNo = 'MBMC/' . $request['service_id'] . '/' . $renewNursingLicense->id . '/' . date('dmY');
                $renewNursingLicense->application_no = $applicationNo;
                $renewNursingLicense->save();

              $status  = Status::create([
                    'service_id' => 2025,
                    'department_id' =>8,
                    'table_id' => $renewNursingLicense->id,
                    'user_id' => Auth::user()->id
                ]);
                $this->commonservice->store_approval_hierarchies($renewNursingLicense, $user, $status);

            }

        DB::commit();
        return [true];

    }

    public function edit($id)
    {
        return RenewalNursingLicense::find($id);
    }

    public function update($request, $id)
    {
        // dd($request->all());
        DB::beginTransaction();
        try {
            // Find the existing record
            $renewNursingLicense = RenewalNursingLicense::find($id);

            // Handle file uploads and update original file names

            $renewNursingLicense->update($request->all());

            DB::commit();
            return [true];
        } catch (\Exception $e) {
            DB::rollback();
            Log::info($e);
            return [false, $e->getMessage()];
        }
    }
}
