<?php

namespace App\Services\Trade;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use App\Models\Trade\PropertyDivisionIntoSubDivision;
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;
use Illuminate\Support\Arr;

class ChangePropertyDivisionService
{
    protected $curlAPiService;
    protected $aapaleSarkarLoginCheckService;
    protected $commonservice;

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

    public function store($request)
    {

        try {
            DB::beginTransaction();
            $user = Auth::user();
            $request['user_id'] = Auth::user()->id;
            $request['service_id'] = "4890";
            $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);
            }
            $data = $request->except('application_no');

            $documentFields = [
                'doc_upload',
                'upload_prescribed_formats',
                'upload_no_due_doc',
                'owner_doc'
            ];

            foreach ($documentFields as $field) {
                $formField = $field . 's';
                if ($request->hasFile($formField)) {
                    $originalFileName = $request->file($formField)->getClientOriginalName();
                    $path = $request->file($formField)->storeAs(
                        "property_division/$formField/",
                        $originalFileName,
                        'public'
                    );
                    $data[$field] = $path;
                }
            }
            $PropertyDivisionIntoSubDivision = PropertyDivisionIntoSubDivision::create($data);

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

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

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

                $payload = [
                    "RTSPostData" => [
                        [
                            "User_Id" => $user->id,
                            "Service_Code" => "4890",
                            "Service" => "Property division into sub-divisions",
                            "Pay_ReferenceNo" => "1",
                            "Pay_Amount" => "1",
                            "Pay_Date" => "22-Jul-2025",
                            "Department_Code" => "4",
                            "Department" => "Property Tax Department",
                            "Status" => 1,
                            "Applicant_English_Name" => $user->name,
                            "Applicant_Marathi_Name" => $user->name,
                            "Applicant_English_Address" => $user->address,
                            "Applicant_Marathi_Address" => $user->address,
                            "Mobile" => $PropertyDivisionIntoSubDivision->mobile_no,
                            "Email" => $PropertyDivisionIntoSubDivision->email,
                            "AadharNo" => $user->aadhar_no,
                            "PropertyNo" => $PropertyDivisionIntoSubDivision->propno,
                            "OwnerName" => $PropertyDivisionIntoSubDivision->property_name,
                            "Property_Address" => $PropertyDivisionIntoSubDivision->property_address,
                            "Property_Area" => $PropertyDivisionIntoSubDivision->property_area,
                            "FlatNo" => $PropertyDivisionIntoSubDivision->flat_no,
                            "WardId" => $PropertyDivisionIntoSubDivision->ward,
                            "ZoneId" => $PropertyDivisionIntoSubDivision->zone,
                            "Total_Outstanding" => $PropertyDivisionIntoSubDivision->outstanding_amt,
                            "Annual_Period" => "2024-2025",
                            "Application_Form" => "mbmc",
                            "Mode" => 1,
                            "Application_No" => $applicationNo,
                            "Application_Status" => $PropertyDivisionIntoSubDivision->application_status ?? "P"
                        ]
                    ]
                ];

                $jsonPayload = json_encode($payload);
                $encryptedString = $this->commonservice->encryptStringProperty($jsonPayload);

                $this->commonservice->propertyDataStrore($encryptedString);
            }

            DB::commit();
            return [true];
        } catch (\Exception $e) {

            Log::error('Error in Property store method: ' . $e->getMessage());
            return [false, $e->getMessage()];
        }
    }


    public function edit($id)
    {

        return PropertyDivisionIntoSubDivision::find($id);
    }

    // public function update_old($request, $id)
    // {
    //     DB::beginTransaction();
    //     try {
    // Find the existing record
    // $PropertyDivisionIntoSubDivision = PropertyDivisionIntoSubDivision::findOrFail($id);
    // Handle file uploads and update original file names
    // if ($request->hasFile('doc_upload')) {
    //     if ($PropertyDivisionIntoSubDivision && Storage::exists($PropertyDivisionIntoSubDivision->doc_upload)) {
    //         Storage::delete($PropertyDivisionIntoSubDivision->doc_upload);
    //     }
    //     $request['doc_upload'] = $request->doc_upload->store('trade/change-license-name');
    // }

    // if ($request->hasFile('upload_prescribed_formats')) {
    //     if ($PropertyDivisionIntoSubDivision && Storage::exists($PropertyDivisionIntoSubDivision->upload_prescribed_formats)) {
    //         Storage::delete($PropertyDivisionIntoSubDivision->upload_prescribed_formats);
    //     }
    //     $request['upload_prescribed_formats'] = $request->upload_prescribed_formats->store('trade/change-license-name');
    // }

    // if ($request->hasFile('upload_no_due_doc')) {
    //     if ($PropertyDivisionIntoSubDivision && Storage::exists($PropertyDivisionIntoSubDivision->upload_no_due_doc)) {
    //         Storage::delete($PropertyDivisionIntoSubDivision->upload_no_due_doc);
    //     }
    //     $request['upload_no_due_doc'] = $request->upload_no_due_doc->store('trade/change-license-name');
    // }

    // if ($request->hasFile('owner_doc')) {
    //     if ($PropertyDivisionIntoSubDivision && Storage::exists($PropertyDivisionIntoSubDivision->owner_doc)) {
    //         Storage::delete($PropertyDivisionIntoSubDivision->owner_doc);
    //     }
    //     $request['owner_doc'] = $request->owner_doc->store('trade/change-license-name');
    // }
    // if ($request->hasFile('doc_upload')) {
    //     if ($PropertyDivisionIntoSubDivision && Storage::exists($PropertyDivisionIntoSubDivision->doc_upload)) {
    //         Storage::delete($PropertyDivisionIntoSubDivision->doc_upload);
    //     }
    //     $request['doc_upload'] = $request->doc_upload->store('trade/change-license-name');
    // }
    // $PropertyDivisionIntoSubDivision->update($request->all());


    // code to send data to department
    //     if ($request->hasFile('doc_upload')) {
    //         $request['doc_upload'] = $this->curlAPiService->convertFileInBase64($request->file('doc_upload'));
    //     } else {
    //         $request['doc_upload'] = "";
    //     }
    //     if ($request->hasFile('doc_upload')) {
    //         $request['doc_upload'] = $this->curlAPiService->convertFileInBase64($request->file('doc_upload'));
    //     } else {
    //         $request['doc_upload'] = "";
    //     }
    //     $request['application_no'] = $PropertyDivisionIntoSubDivision->application_no;
    //     $request['user_id'] =  (Auth::user()->user_id && Auth::user()->user_id != "") ? "" . Auth::user()->user_id . "" : "" . Auth::user()->id . "";
    //     $newData = $request->except(['_token', '_method', 'id', 'application_documents', 'no_dues_documents']);
    //     $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.trade') . 'SHELMicroService/SHELApi/ApleSarkarService/UpdateLicenseNameChangeFORPMC', '');

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

    //     if (isset($data['status']) && $data['status'] == "200") {
    //         // Access the application_no
    //         DB::commit();
    //         return [true];
    //     } else {
    //         DB::rollback();
    //         return [false, $data['error']];
    //     }
    //     // end of code to send data to department
    //     } catch (\Exception $e) {
    //         DB::rollback();
    //         Log::info($e);
    //         return [false, $e->getMessage()];
    //     }
    // }



    public function update($request, $id)
    {
        // dd($request->all());
        DB::beginTransaction();
        try {
            // Find the existing record
            $PropertyDivisionIntoSubDivision = PropertyDivisionIntoSubDivision::find($id);

            // Handle file uploads and update original file names

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

            DB::commit();
            return [true];
        } catch (\Exception $e) {
            DB::rollback();
            Log::info($e);
            return [false, $e->getMessage()];
        }
    }
}
