<?php

namespace App\Services\PropertyTax;

use App\Models\PropertyTax\TransferSelfPropertyCertificate;
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 TransferSelfPropertyCertificateService
{
    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'] = '5890';

            $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/transfer-property', 'public');
            // }
            // if ($request->hasFile('certificate_of_no_duess')) {
            //     $request['certificate_of_no_dues'] = $request->certificate_of_no_duess->store('property-tax/transfer-property', 'public');
            // }
            // if ($request->hasFile('copy_of_documents')) {
            //     $request['copy_of_document'] = $request->copy_of_documents->store('property-tax/transfer-property', 'public');
            // }



            $documentFields = [
                'uploaded_application',
                'certificate_of_no_dues',
                'copy_of_document',

            ];

            foreach ($documentFields as $field) {
                $formField = $field . 's'; // expects input name like 'lease_agreements'
                if ($request->hasFile($formField)) {
                    $originalFileName = $request->file($formField)->getClientOriginalName();
                    $request[$field] = $request->file($formField)->storeAs("transfer_selfproperty/$formField/", $originalFileName, 'public');
                }
            }


            $request['date_of_registration_document'] = date('Y-m-d', strtotime($request->date_of_registration_document));
            $transferPropertyCertificate = TransferSelfPropertyCertificate::create($request->except('application_no'));
            if ($transferPropertyCertificate) {
                $applicationNo = 'MBMC/' . $request['service_id'] . '/' . $transferPropertyCertificate->id . '/' . date('dmY');
                $transferPropertyCertificate->application_no = $applicationNo;
                $transferPropertyCertificate->save();

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

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

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

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

        try {
            $transferPropertyCertificate = TransferSelfPropertyCertificate::find($request->id);
            if ($request->hasFile('uploaded_applications')) {
                if ($transferPropertyCertificate && Storage::exists($transferPropertyCertificate->uploaded_application)) {
                    Storage::delete($transferPropertyCertificate->uploaded_application);
                }
                $request['uploaded_application'] = $request->uploaded_applications->store('property-tax/transfer-property');
            }
            if ($request->hasFile('certificate_of_no_duess')) {
                if ($transferPropertyCertificate && Storage::exists($transferPropertyCertificate->certificate_of_no_dues)) {
                    Storage::delete($transferPropertyCertificate->certificate_of_no_dues);
                }
                $request['certificate_of_no_dues'] = $request->certificate_of_no_duess->store('property-tax/transfer-property');
            }
            if ($request->hasFile('copy_of_documents')) {
                if ($transferPropertyCertificate && Storage::exists($transferPropertyCertificate->copy_of_document)) {
                    Storage::delete($transferPropertyCertificate->copy_of_document);
                }
                $request['copy_of_document'] = $request->copy_of_documents->store('property-tax/transfer-property');
            }
            $transferPropertyCertificate->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'] = "";
            }
            if ($request->hasFile('copy_of_documents')) {
                $request['copy_of_document'] = $this->curlAPiService->convertFileInBase64($request->file('copy_of_documents'));
            } else {
                $request['copy_of_document'] = "";
            }
            $request['application_no'] = $transferPropertyCertificate->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', 'certificate_of_no_duess', 'copy_of_documents']);
            $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.propertyTax') . 'AapaleSarkarAPI/TransferOfPropertyCertificate.asmx/RequestForUpdateTransferOfPropertyCertificate', '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()];
        }
    }
}
