<?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\GrantNursingLicense;
use App\Models\ServiceCredential;
use App\Models\Status;
use App\Services\CommonService;

class GrantNursingLicenseService
{
    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'] = "2024";

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

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

            $status =  Status::create([
                'service_id' => 2024,
                'department_id' => 8,
                'table_id' => $grantNursingLicense->id,
                'user_id' => Auth::user()->id
            ]);

            $this->commonservice->store_approval_hierarchies($grantNursingLicense, $user, $status);
        }

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

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

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

            // Handle file uploads and update original file names

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

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