<?php

namespace App\Services\MedicalHealth;

// use App\Models\MedicalHealth\CivilLocalSelfGovernmentNomination;
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\CivilLocalSelfGovernmentNomination;
use App\Models\ServiceCredential;
use App\Models\Status;
use App\Services\CommonService;

class CivilLocalSelfGovermentServices
{
    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'] = "8929";

        if ($request->hasFile('prescribed_formats')) {
            $request['prescribed_format'] = $request->prescribed_formats->store('health-department/civil-local-self-government', 'public');
        }
        $civillocalselfgovernment = CivilLocalSelfGovernmentNomination::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' => 8929,
                    'department_id' =>8,
                    'table_id' => $civillocalselfgovernment->id,
                    'user_id' => Auth::user()->id
                ]);
                $this->commonservice->store_approval_hierarchies($civillocalselfgovernment, $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()];
        }
    }
}
