<?php

namespace App\Services\PropertyTax;

use App\Models\PropertyTax\TaxExemption;
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\CommonService;
use App\Services\AapaleSarkarLoginCheckService;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;
use App\Models\Status;

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

             $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-exemption','public');
            }
            if ($request->hasFile('uploaded_applications')) {
                $request['uploaded_application'] = $request->uploaded_applications->store('property-tax/tax-exemption','public');
            }
            $request['date_of_commencement'] = date('Y-m-d', strtotime($request->date_of_commencement));
            $taxExemption = TaxExemption::create($request->except('upic_id'));
            if($taxExemption){

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

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

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

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

        try {
            $taxExemption = TaxExemption::find($request->id);

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

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

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

            $request['application_no'] = $taxExemption->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/PropertyTaxExemption.asmx/RequestForUpdatePropertyTaxExemption', '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()];
        }
    }
}
