<?php

namespace App\Services\PropertyTax;

use App\Models\PropertyTax\PropertyTaxAssessment;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
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 PropertyTaxAssessmentService
{
    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();
            $request['user_id'] = $user->id;
            $request['service_id'] = '3';

            $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/tax-assessment', 'public');
            }

            if ($request->hasFile('certificate_of_no_duess')) {
                $request['certificate_of_no_dues'] = $request->certificate_of_no_duess->store('property-tax/tax-assessment', 'public');
            }

            $propertyTaxAssessment = PropertyTaxAssessment::create($request->except('application_no'));

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

                $status = Status::create([
                    'service_id' => 3,
                    'department_id' => 4,
                    'table_id' => $propertyTaxAssessment->id,
                    'user_id' => $user->id
                ]);

                $this->commonservice->store_approval_hierarchies($propertyTaxAssessment, $user, $status);

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

                $jsonPayload = json_encode($payload);

                $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 PropertyTaxAssessment::find($id);
    }

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

        try {
            $propertyTax = PropertyTaxAssessment::find($request->id);

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

            if ($request->hasFile('certificate_of_no_duess')) {
                if ($propertyTax && Storage::exists($propertyTax->certificate_of_no_dues)) {
                    Storage::delete($propertyTax->certificate_of_no_dues);
                }
                $request['certificate_of_no_dues'] = $request->certificate_of_no_duess->store('property-tax/tax-assessment');
            }
            $propertyTax->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('certificate_of_no_duess')) {
                $request['certificate_of_no_dues'] = $this->curlAPiService->convertFileInBase64($request->file('certificate_of_no_duess'));
            } else {
                $request['certificate_of_no_dues'] = "";
            }
            $request['application_no'] = $propertyTax->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', 'certificate_of_no_duess', 'uploaded_applications']);

            $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.propertyTax') . 'AapaleSarkarAPI/PropertyTaxAssessment.asmx/RequestForUpdatePropertyTaxAssessment', 'applicantDetails');

            // 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()];
        }
    }
}
