<?php

namespace App\Services\DrinageWater;

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

class SeweragePropertiesService
{
    protected $aapaleSarkarLoginCheckService;
    protected $commonservice;

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


    public function store($request)
    {
           $data = $request->all();

            $data['user_id'] = Auth::id();
            $data['service_id'] = 8926;

            $fileFields = [
                'application_doc'   => 'application_doc',
                'bill_doc' => 'bill_doc',
                'site_photo'=>'site_photo',
                'blue_print'=>'blue_print',
               'other_doc'=>'other_doc',
               'upload_site_photo' => 'upload_site_photo',
            ];

            foreach ($fileFields as $input => $column) {
                if ($request->hasFile($input)) {
                    $data[$column] = $request->file($input)->store('SewerageProperty/Property', 'public');
                }
            }

            $filteredData = collect($data)->except('application_no')->toArray();

            $grantingTelecom = SewerageProperty::create($filteredData);


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

            $status = Status::create([
                    'service_id' =>8926,
                    'department_id' =>12,
                    '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 SewerageProperty::find($id);
    }

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

            // Handle file uploads and update original file names

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

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