<?php

namespace App\Services\PropertyTax;

use App\Models\PropertyTax\TaxDemand;
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 TaxDemandService
{
    protected $curlAPiService;
    protected $commonservice;
    protected $aapaleSarkarLoginCheckService;

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

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

        try {

            $user = Auth::user();
            $request['user_id'] = Auth::user()->id;
            $request['service_id'] = '6';

             $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-demand','public');
            }
            $taxDemand = TaxDemand::create($request->except('application_no'));
            if($taxDemand){

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

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

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

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

        try {
            $taxDemand = TaxDemand::find($request->id);
            if ($request->hasFile('uploaded_applications')) {
                if ($taxDemand && Storage::exists($taxDemand->uploaded_application)) {
                    Storage::delete($taxDemand->uploaded_application);
                }
                $request['uploaded_application'] = $request->uploaded_applications->store('property-tax/tax-demand');
            }
            $taxDemand->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'] = "";
            }
            $request['application_no'] = $taxDemand->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', 'uploaded_applications']);
            $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.propertyTax') . 'AapaleSarkarAPI/TaxDemands.asmx/RequestForUpdateTaxDemands', 'TaxDemandss');

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