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

class CityCleanService
{
    protected $aapaleSarkarLoginCheckService;
    protected $commonservice;

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


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

            if ($request->hasFile('geo_photo')) {
                $request['geo_photos'] = $request->geo_photo->store('CityClean/keepclean', 'public');
            }

            if ($request->hasFile('upload_prescribed_doc')) {
                $request['upload_prescribed_docs'] = $request->upload_prescribed_doc->store('CityClean/keepclean', 'public');
            }

            $grantNursingLicense = CityClean::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' => 9396,
                    'department_id' => 14,
                    'table_id' => $grantNursingLicense->id,
                    'user_id' => $user->id
                ]);
                $this->commonservice->store_approval_hierarchies($grantNursingLicense, $user, $status);
            }

            DB::commit();
            return [true];
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Error in store method: ' . $e->getMessage());
            return [false, $e->getMessage()];
        }
    }

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

    public function update($request, $id)
    {
        // dd($request->all());
        DB::beginTransaction();
        try {
            // Find the existing record
            $grantNursingLicense = CityClean::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()];
        }
    }
}
