<?php

namespace App\Services\PropertyTax;

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

class SelfAssessmentService
{
    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'] = "9";

            $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/self-assessment', 'public');
            }
            $selfAssessment = SelfAssessment::create($request->except('application_no'));
            if ($selfAssessment) {
                $applicationNo = 'MBMC/' . $request['service_id'] . '/' . $selfAssessment->id . '/' . date('dmY');
                $selfAssessment->application_no = $applicationNo;
                $selfAssessment->save();

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

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

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

        try {
            $selfAssessment = SelfAssessment::find($request->id);

            if ($request->hasFile('uploaded_applications')) {
                if ($selfAssessment && Storage::exists($selfAssessment->uploaded_application)) {
                    Storage::delete($selfAssessment->uploaded_application);
                }
                $request['uploaded_application'] = $request->uploaded_applications->store('property-tax/self-assessment', 'public');
            }
            $selfAssessment->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'] = $selfAssessment->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/SelfAssessmentService.asmx/RequestForUpdateSelfAssessmentService', 'applicantDetails');

            // Decode JSON string to PHP array
            $data = json_decode($data, true);

            if (isset($data['d']['Status']) && $data['d']['Status'] != "") {
                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()];
        }
    }
}
