<?php

namespace App\Services\PropertyTax;

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

class NoDueCertificateService
{
    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'] = "2";

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

    //         // Handle receipt_docs file upload
    //         if ($request->hasFile('receipt_docs')) {
    //             $request['receipt_doc'] = $request->file('receipt_docs')->store('property-tax/no-due', 'public');
    //         }

    //         // Handle prescribed_docs file upload
    //         if ($request->hasFile('prescribed_docs')) {
    //             $request['prescribed_doc'] = $request->file('prescribed_docs')->store('property-tax/no-due', 'public');
    //         }

    //         // Create No Due Certificate (excluding application_no)
    //         $noDueCertificate = NoDueCertificate::create($request->except('application_no'));

    //         // Generate application number and save
    //         if ($noDueCertificate) {
    //             $applicationNo = 'MBMC/' . $request['service_id'] . '/' . $noDueCertificate->id . '/' . date('dmY');
    //             $noDueCertificate->update(['application_no' => $applicationNo]);

    //             // Create status
    //             $status = Status::create([
    //                 'service_id' => 2,
    //                 'department_id' => 4,
    //                 'table_id' => $noDueCertificate->id,
    //                 'user_id' => $user->id
    //             ]);

    //             // Store approval hierarchies
    //             $this->commonservice->store_approval_hierarchies($noDueCertificate, $user, $status);
    //         }

    //         DB::commit();

    //         return [true];
    //     } catch (\Exception $e) {
    //         DB::rollBack();
    //         Log::error('NoDueCertificate Store Error: ' . $e->getMessage(), ['exception' => $e]);
    //         return [false, $e->getMessage()];
    //     }
    // }

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

        try {
            $user = Auth::user();

            $request['user_id'] = $user->id;
            $request['service_id'] = "2";

            $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('receipt_docs')) {
                $request['receipt_doc'] = $request->file('receipt_docs')->store('property-tax/no-due', 'public');
            }

            if ($request->hasFile('prescribed_docs')) {
                $request['prescribed_doc'] = $request->file('prescribed_docs')->store('property-tax/no-due', 'public');
            }

            $noDueCertificate = NoDueCertificate::create($request->except('application_no'));

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

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

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

                $payload = [
                    "RTSPostData" => [
                        [
                            "User_Id" => $user->id,
                            "Service_Code" => "2",
                            "Service" => "No Dues Certificate (Property)",
                            "Pay_ReferenceNo" => "1",
                            "Pay_Amount" => "1",
                            "Pay_Date" => "22-Jul-2025",
                            "Department_Code" => "4",
                            "Department" => "Property Tax Department",
                            "Status" => 1,
                            "Applicant_English_Name" => $noDueCertificate->applicant_name_eng,
                            "Applicant_Marathi_Name" => $noDueCertificate->applicant_name_eng,
                            "Applicant_English_Address" => $user->address,
                            "Applicant_Marathi_Address" => $user->address,
                            "Mobile" => $noDueCertificate->applicant_mobile_no,
                            "Email" => $noDueCertificate->email_id,
                            "AadharNo" => $user->aadhar_no,
                            "PropertyNo" => $noDueCertificate->property_address,
                            "OwnerName" => $noDueCertificate->owner_name,
                            "Property_Address" => $noDueCertificate->owner_full_add,
                            "Property_Area" => $noDueCertificate->property_no,
                            "FlatNo" => $noDueCertificate->index_number,
                            "WardId" => $noDueCertificate->ward,
                            "ZoneId" => $noDueCertificate->zone,
                            "Total_Outstanding" => $noDueCertificate->uploaded_application,
                            "Annual_Period" => $noDueCertificate->annual_period,
                            "Application_Form" => "mbmc",
                            "Mode" => 1,
                            "Application_No" => $applicationNo,
                            "Application_Status" => $noDueCertificate->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::error('NoDueCertificate Store Error: ' . $e->getMessage(), ['exception' => $e]);
            return [false, $e->getMessage()];
        }
    }




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

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

        try {
            $noDueCertificate = NoDueCertificate::find($request->id);

            if ($request->hasFile('uploaded_applications')) {
                if ($noDueCertificate && Storage::exists($noDueCertificate->uploaded_application)) {
                    Storage::delete($noDueCertificate->uploaded_application);
                }
                $request['uploaded_application'] = $request->uploaded_applications->store('property-tax/no-due');
            }
            $noDueCertificate->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['user_id'] = (Auth::user()->user_id && Auth::user()->user_id != "") ? Auth::user()->user_id : Auth::user()->id;
            $request['application_no'] = $noDueCertificate->application_no;
            $newData = $request->except(['_token', 'id', 'uploaded_applications']);

            $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.propertyTax') . 'AapaleSarkarAPI/NoDueCertificate.asmx/RequestForUpdateNoDueCertificate', '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()];
        }
    }
}
