<?php

namespace App\Services\WaterDepartment;

use App\Mail\SendMail;
use App\Models\Status;
use App\Services\CommonService;
use App\Services\CurlAPiService;
use App\Models\ServiceCredential;
use App\Models\WaterPrabhagWards;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use App\Services\AapaleSarkarLoginCheckService;
use App\Models\WaterDepartment\Waternewconnection;

class NewWaterConnectionService
{
    protected $curlAPiService;
    protected $aapaleSarkarLoginCheckService;
    protected $commonService;

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



    public function store($request)
    {
        DB::beginTransaction();

        try {

            $user = Auth::user();
            $data = $request->all();

            $data['user_id'] = Auth::user()->id;
            $data['service_id'] = "21";
            $data['ward_area'] = WaterPrabhagWards::where('id', $request->wards)->value('id'); // returns a single value instead of a collection

            $fileFields = [
                    'written_application_document',
                    'ownership_document',
                    'address_proof',
                    'stamp_karnama',
                    'oc_and_cc',
                    'structure_photo',
                ];

            foreach ($fileFields as $field) {
                if ($request->hasFile($field)) {
                    $file = $request->file($field);
                    $filename = time() . '_' . $file->getClientOriginalName();
                    $path = $file->storeAs('water-department/new-water-connection', $filename, 'public');
                    $data[$field] = $path;
                }
            }


            // $waterdata =  [
            //         "jsonData" => [
            //             [
            //                 "MerchantID" => "MBMCCORE",
            //                 "connno" => "D022023MBMC"
            //             ]
            //         ]
            //     ];

            //  $jsonData = json_encode($waterdata);


            //     $encryptedData = $this->commonService->encryptString($jsonData);

            //     $apidata = $this->commonService->sendEncryptedWaterData($encryptedData);
            //     return response()->json([

            //         'jsonData' => [
            //             'encr_request' => $apidata,
            //         ]
            //     ]);
            $filteredData = collect($data)->except('application_no')->toArray();
            $waternewconnection = Waternewconnection::create($filteredData);
            if($waternewconnection){
                $applicationNo = 'MBMC/' . $data['service_id'] . '/' . $waternewconnection->id . '/' . date('dmY');
                $waternewconnection->application_no = $applicationNo;
                $waternewconnection->save();

                $status = Status::create([
                    'user_id' => $user->id,
                    'service_id' =>21,
                    'department_id' =>5,
                    'table_id' => $waternewconnection->id
                ]);

                $this->commonService->store_approval_hierarchies($waternewconnection, $user, $status);
            }

            DB::commit();
            return [true];
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Error in store method: ' . $e->getMessage());
            return [false, $e->getMessage()];
        }
    }

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

    public function update($request, $id)
    {
        DB::beginTransaction();
        try {
            // Find the existing record
            $newWaterConnection = Waternewconnection::findOrFail($id);
            // Handle file uploads and update original file names
            if ($request->hasFile('written_application_documents')) {
                if ($newWaterConnection && Storage::exists($newWaterConnection->written_application_document)) {
                    Storage::delete($newWaterConnection->written_application_document);
                }
                $request['written_application_document'] = $request->written_application_documents->store('water-department/new-water-connection');
            }
            if ($request->hasFile('ownership_documents')) {
                if ($newWaterConnection && Storage::exists($newWaterConnection->ownership_document)) {
                    Storage::delete($newWaterConnection->ownership_document);
                }
                $request['ownership_document'] = $request->ownership_documents->store('water-department/new-water-connection');
            }
            if ($request->hasFile('no_dues_documents')) {
                if ($newWaterConnection && Storage::exists($newWaterConnection->no_dues_document)) {
                    Storage::delete($newWaterConnection->no_dues_document);
                }
                $request['no_dues_document'] = $request->no_dues_documents->store('water-department/new-water-connection');
            }



            if ($request->hasFile('address_proofs')) {
                if ($newWaterConnection && Storage::exists($newWaterConnection->address_proof)) {
                    Storage::delete($newWaterConnection->address_proof);
                }
                $request['address_proof'] = $request->address_proofs->store('water-department/new-water-connection');
            }
            // Update the rest of the fields
            $newWaterConnection->update($request->all());


            // code to send data to department
            if ($request->hasFile('application_documents')) {
                $request['application_document'] = $this->curlAPiService->convertFileInBase64($request->file('application_documents'));
            } else {
                $request['application_document'] = "";
            }
            if ($request->hasFile('ownership_documents')) {
                $request['ownership_document'] = $this->curlAPiService->convertFileInBase64($request->file('ownership_documents'));
            } else {
                $request['ownership_document'] = "";
            }
            if ($request->hasFile('nodues_documents')) {
                $request['nodues_document'] = $this->curlAPiService->convertFileInBase64($request->file('nodues_documents'));
            } else {
                $request['nodues_document'] = "";
            }
            $request['application_no'] = $newWaterConnection->application_no;
            $request['user_id'] = (Auth::user()->user_id && Auth::user()->user_id != "") ? Auth::user()->user_id : Auth::user()->id;
            $newData = $request->except(['_token', 'id', 'application_documents', 'ownership_documents', 'nodues_documents']);
            $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.water') . 'WaterBillMicroService/WaterbillApi/ApleSarkarService/RequestForUpdateNewWaterConnection', '');

            // Decode JSON string to PHP array
            $data = json_decode($data, true);

            if (isset($data['status']) && $data['status'] == "200") {
                // Access the application_no
                DB::commit();
                return [true];
            } else {
                DB::rollback();
                return [false, $data['error']];
            }
            // end of code to send data to department
        } catch (\Exception $e) {
            DB::rollback();
            Log::info($e);
            return [false, $e->getMessage()];
        }
    }
}
