<?php

namespace App\Services\PropertyTax;

use App\Mail\SendMail;
use App\Models\Status;
use App\Services\CommonService;
use App\Services\CurlAPiService;
use App\Models\ServiceCredential;
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\PropertyTax\RegistrationOfObjection;

class RegistrationOfObjectionService
{
    protected $curlAPiService;
    protected $commonservice;
    protected $aapaleSarkarLoginCheckService;

    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();
            $request['user_id'] = Auth::user()->id;
            $request['service_id'] = '10';

             $ward = DB::table('prabhag_wards')
                ->where('ward_name', $request->ward_area)
                ->first();

            if ($ward) {
                $request['ward_area'] = $ward->id;
            } else {
                throw new \Exception("Ward not found for name: " . $request->ward_area);
            }

            if ($request->hasFile('uploaded_applications')) {
                $request['uploaded_application'] = $request->uploaded_applications->store('property-tax/reg-of-obj','public');
            }
            if ($request->hasFile('no_dues_documents')) {
                $request['no_dues_document'] = $request->no_dues_documents->store('property-tax/reg-of-obj','public');
            }
            $registrationOfObjection = RegistrationOfObjection::create($request->except('application_no'));
            if($registrationOfObjection){

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

              $status  = Status::create([
                    'service_id' =>10,
                    'department_id' =>4,
                    'table_id' => $registrationOfObjection->id,
                    'user_id' => Auth::user()->id
                ]);
                 $this->commonservice->store_approval_hierarchies($registrationOfObjection, $user, $status);

                    $payload = [
                    "RTSPostData" => [
                        [
                            "User_Id" => $user->id,
                            "Service_Code" => "10",
                            "Service" => "Registration of objection",
                            "Pay_ReferenceNo" => "1",
                            "Pay_Amount" => "1",
                            "Pay_Date" => "22-Jul-2025",
                            "Department_Code" => "4",
                            "Department" => "Property Tax Department",
                            "Status" => 1,
                            "Applicant_English_Name" => $registrationOfObjection->applicant_full_name,
                            "Applicant_Marathi_Name" => $registrationOfObjection->applicant_full_name,
                            "Applicant_English_Address" => $user->address,
                            "Applicant_Marathi_Address" => $user->address,
                            "Mobile" => $registrationOfObjection->applicant_mobile_no,
                            "Email" => $registrationOfObjection->email_id,
                            "AadharNo" => $user->aadhar_no,
                            "PropertyNo" => $registrationOfObjection->property_no,
                            "OwnerName" => $registrationOfObjection->property_owner_name,
                            "Property_Address" => $registrationOfObjection->property_address,
                            "Property_Area" => $registrationOfObjection->property_no,
                            "FlatNo" => $registrationOfObjection->house_no,
                            "WardId" => $registrationOfObjection->ward,
                            "ZoneId" => $registrationOfObjection->zone,
                            "Total_Outstanding" => $registrationOfObjection->index_number,
                            "Annual_Period" => "2024-2025",
                            "Application_Form" => "mbmc",
                            "Mode" => 1,
                            "Application_No" => $applicationNo,
                            "Application_Status" => $registrationOfObjection->application_status ?? "P"
                        ]
                    ]
                ];

                $jsonPayload = json_encode($payload);
// dd($jsonPayload);
                $encryptedString = $this->commonservice->encryptStringProperty($jsonPayload);

                $this->commonservice->propertyDataStrore($encryptedString);
            }




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

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

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

        try {
            $registrationOfObjection = RegistrationOfObjection::find($request->id);
            if ($request->hasFile('uploaded_applications')) {
                if ($registrationOfObjection && Storage::exists($registrationOfObjection->uploaded_application)) {
                    Storage::delete($registrationOfObjection->uploaded_application);
                }
                $request['uploaded_application'] = $request->uploaded_applications->store('property-tax/reg-of-obj');
            }
            if ($request->hasFile('no_dues_documents')) {
                if ($registrationOfObjection && Storage::exists($registrationOfObjection->no_dues_document)) {
                    Storage::delete($registrationOfObjection->no_dues_document);
                }
                $request['no_dues_document'] = $request->no_dues_documents->store('property-tax/reg-of-obj');
            }
            $registrationOfObjection->update($request->all());



            // code to send data to department
            if ($request->hasFile('uploaded_applications')) {
                $request['uploaded_application'] = $this->curlAPiService->convertFileInBase64($request->file('uploaded_applications'));
            } else {
                $request['uploaded_application'] = "";
            }

            if ($request->hasFile('no_dues_documents')) {
                $request['no_dues_document'] = $this->curlAPiService->convertFileInBase64($request->file('no_dues_documents'));
            } else {
                $request['no_dues_document'] = "";
            }
            $request['application_no'] = $registrationOfObjection->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', 'no_dues_documents', 'uploaded_applications']);
            $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.propertyTax') . 'AapaleSarkarAPI/FileAnObjection.asmx/RequestForUpdateFileAnObjection', 'fileanobjection');

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

            if (isset($data['d']['Status']) && $data['d']['Status'] == "200") {
                DB::commit();
                return [true];
            } else {
                DB::rollback();
                if (isset($data['d']['Error']) || isset($data['d'])) {
                    return [false, $data['d']['Error'] ?? $data['d']];
                } else {
                    return [false, "Something went wrong, please try again"];
                }
            }
            // end of code to send data to department
        } catch (\Exception $e) {
            DB::rollback();
            Log::info($e);
            return [false, $e->getMessage()];
        }
    }
}
