<?php

namespace App\Services\PwdElectrical;

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


class VikasKamachaGopniyDakhlaService
{
    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'] = "5042";


        $documentFields = [
            'work_order_doc',
            'work_completion_doc',
            'nigarmit_doc',
            'company_registration_doc'
        ];

        foreach ($documentFields as $field) {
            $formField = $field . 's';
            if ($request->hasFile($formField)) {
                $originalFileName = $request->file($formField)->getClientOriginalName();

                $request[$field] = $request->file($formField)->storeAs("pwd_electrical/$formField/", $originalFileName, 'public');
            }
        }


        $grantingTelecom = VikasKamachGopniyDakhla::create($request->except('application_no'));


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

              $status =  Status::create([
                    'service_id' =>5042,
                    'department_id' =>10,
                    'table_id' => $grantingTelecom->id,
                      'user_id' => Auth::user()->id
                ]);

                 $this->commonservice->store_approval_hierarchies($grantingTelecom, Auth::user(), $status);
            }


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

    }



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

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

            // Handle file uploads and update original file names

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

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