<?php

namespace App\Services\Pwd;

use App\Models\PwdElectrical\PathRoadCitizenshipCertificate;
use App\Services\AapaleSarkarLoginCheckService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Models\ServiceCredential;
use App\Models\Status;



class PathRoadCitizienshipService
{
    protected $aapaleSarkarLoginCheckService;

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



    public function store(Request $request)
    {

        $request['user_id'] = Auth::user()->id;
        $request['service_id'] = "3042";


        $documentFields = [
            'plan_copy',
            'side_visit_geotag_pic',
            'property_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 = PathRoadCitizenshipCertificate::create($request->except('application_no'));

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

            Status::create([
                'service_id' => 3042,
                'department_id' => 4,
                'table_id' => $grantingTelecom->id
            ]);
        }


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

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

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

            // Handle file uploads and update original file names

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

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