<?php

namespace App\Services\DrinageWater;

use App\Models\DrinageWater\WaterRepair;
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 WaterRepairService
{
    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'] = 8922;

            $fileFields = [
                'application_documents'   => 'application_documents',
            ];

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

       $filteredData = collect($data)->except('application_no')->toArray();
        $grantingTelecom = WaterRepair::create($filteredData);

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

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

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

            // Handle file uploads and update original file names

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

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