<?php

namespace App\Services\PropertyTax;

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

class TaxExemptionNonResidentPropertiesService
{
    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'] = '11';

             $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('no_dues_documents')) {
                $request['no_dues_document'] = $request->no_dues_documents->store('property-tax/tax-demand');
            }
            if ($request->hasFile('uploaded_applications')) {
                $request['uploaded_application'] = $request->uploaded_applications->store('property-tax/tax-demand');
            }
            $taxExemptionNonResidentProperties = TaxExemptionNonResidentProperties::create($request->except('application_no'));

            if($taxExemptionNonResidentProperties){

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

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

                $payload = [
                                "RTSPostData" => [
                                    [
                                        "User_Id" => $user->id,
                                        "Service_Code" => "11",
                                        "Service" => "Tax exemption for non-resident",
                                        "Pay_ReferenceNo" => "1",
                                        "Pay_Amount" => "1",
                                        "Pay_Date" => "22-Jul-2025",
                                        "Department_Code" => "4",
                                        "Department" => "Property Tax Department",
                                        "Status" => 1,
                                        "Applicant_English_Name" => $taxExemptionNonResidentProperties->applicant_full_name,
                                        "Applicant_Marathi_Name" => $taxExemptionNonResidentProperties->applicant_full_name,
                                        "Applicant_English_Address" => $user->address,
                                        "Applicant_Marathi_Address" => $user->address,
                                        "Mobile" => $taxExemptionNonResidentProperties->applicant_mobile_no,
                                        "Email" => $taxExemptionNonResidentProperties->email_id,
                                        "AadharNo" => $user->aadhar_no,
                                        "PropertyNo" => $taxExemptionNonResidentProperties->property_no,
                                        "OwnerName" => $taxExemptionNonResidentProperties->property_owner_name,
                                        "Property_Address" => $taxExemptionNonResidentProperties->property_address,
                                        "Property_Area" => $taxExemptionNonResidentProperties->property_area,
                                        "FlatNo" => $taxExemptionNonResidentProperties->house_no,
                                        "WardId" => $taxExemptionNonResidentProperties->ward,
                                        "ZoneId" => $taxExemptionNonResidentProperties->zone,
                                        "Total_Outstanding" => $taxExemptionNonResidentProperties->upic_id,
                                        "Annual_Period" => "2024-2025",
                                        "Application_Form" => "mbmc",
                                        "Mode" => 1,
                                        "Application_No" => $applicationNo,
                                        "Application_Status" => $taxExemptionNonResidentProperties->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 TaxExemptionNonResidentProperties::find($id);
    }

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

        try {
            $taxExemptionNonResidentProperties = TaxExemptionNonResidentProperties::find($request->id);

            if ($request->hasFile('no_dues_documents')) {
                if ($taxExemptionNonResidentProperties && Storage::exists($taxExemptionNonResidentProperties->no_dues_document)) {
                    Storage::delete($taxExemptionNonResidentProperties->no_dues_document);
                }
                $request['no_dues_document'] = $request->no_dues_documents->store('property-tax/tax-demand');
            }
            if ($request->hasFile('uploaded_applications')) {
                if ($taxExemptionNonResidentProperties && Storage::exists($taxExemptionNonResidentProperties->uploaded_application)) {
                    Storage::delete($taxExemptionNonResidentProperties->uploaded_application);
                }
                $request['uploaded_application'] = $request->uploaded_applications->store('property-tax/tax-demand');
            }

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

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

            if ($request->hasFile('uploaded_applications')) {
                $request['uploaded_application'] = $this->curlAPiService->convertFileInBase64($request->file('uploaded_applications'));
            } else {
                $request['uploaded_application'] = "";
            }

            $request['application_no'] = $taxExemptionNonResidentProperties->application_no;
            $request['user_id'] = (Auth::user()->user_id && Auth::user()->user_id != "") ? Auth::user()->user_id : Auth::user()->id;
            $request['service_id'] = '11';
            $newData = $request->except(['_token', 'id', 'uploaded_applications', 'no_dues_documents']);
            $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.propertyTax') . 'AapaleSarkarAPI/TaxExemptionForNonResidentProperties.asmx/RequestForUpdateTaxExemptionForNonResidentProperties', 'applicantDetails');

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

            if (isset($data['d']['Status']) && $data['d']['Status'] == "200") {
                // Access the application_no
                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()];
        }
    }
}
