<?php

namespace App\Services\MedicalHealth;

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

class ChangeNursingLicenseService
{
    protected $aapaleSarkarLoginCheckService;
    protected $commonservice;

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


    public function store($request)
    {

        $request['user_id'] = Auth::user()->id;
        $request['service_id'] = "2026";

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

         if($civillocalselfgovernment){

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

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

            }

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

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

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

            // Handle file uploads and update original file names

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

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