<?php

namespace App\Services\Nulm;

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


class HawkerRegisterService
{
    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'] = "2031";

        if ($request->hasFile('images')) {
            $request['image'] = $request->images->store('hawker');
        }
        if ($request->hasFile('prescribed_docs')) {
            $request['prescribed_doc'] = $request->prescribed_docs->store('hawker');
        }
        $hawkerRegister=HawkerRegister::create($request->except('application_no'));

        if($hawkerRegister){

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

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

        }



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


    }

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

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

            // Handle file uploads and update original file names

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

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