<?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\TradeLicense;
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 TradeLicenseService
{
    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 {
            $request['user_id'] = Auth::user()->id;
            $request['service_id'] = "8928";
            if ($request->hasFile('application_documents')) {
                $request['application_document'] = $request->application_documents->store('trade/trade-license','public');
            }
            if ($request->hasFile('no_dues_documents')) {
                $request['no_dues_document'] = $request->no_dues_documents->store('trade/trade-license','public');
            }
            if ($request->hasFile('prescribed_docs')) {
                $request['prescribed_doc'] = $request->prescribed_docs->store('trade/trade-license', 'public');
            }
            $tradeRenewalLicensePermission = TradeLicense::create($request->except('application_no'));
             if($tradeRenewalLicensePermission){

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

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

            }



            DB::commit();
            return [true];
        } catch (\Exception $e) {
            DB::rollback();
            Log::error('Error in store method: ' . $e->getMessage());
            return [false, $e->getMessage()];
        }
    }


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

    public function update($request, $id)
    {
        DB::beginTransaction();
        try {
            // Find the existing record
            $tradeRenewalLicensePermission = TradeLicense::findOrFail($id);
            // Handle file uploads and update original file names
            if ($request->hasFile('application_documents')) {
                if ($tradeRenewalLicensePermission && Storage::exists($tradeRenewalLicensePermission->application_document)) {
                    Storage::delete($tradeRenewalLicensePermission->application_document);
                }
                $request['application_document'] = $request->application_documents->store('trade/trade-license');
            }
            if ($request->hasFile('no_dues_documents')) {
                if ($tradeRenewalLicensePermission && Storage::exists($tradeRenewalLicensePermission->no_dues_document)) {
                    Storage::delete($tradeRenewalLicensePermission->no_dues_document);
                }
                $request['no_dues_document'] = $request->no_dues_documents->store('trade/trade-license');
            }
            $tradeRenewalLicensePermission->update($request->all());

            // code to send data to department
            if ($request->hasFile('application_documents')) {
                $request['application_document'] = $this->curlAPiService->convertFileInBase64($request->file('application_documents'));
            } else {
                $request['application_document'] = "";
            }
            if ($request->hasFile('no_dues_documents')) {
                $request['no_dues_document'] = $this->curlAPiService->convertFileInBase64($request->file('no_dues_documents'));
            } else {
                $request['no_dues_document'] = "";
            }

            $request['application_no'] = $tradeRenewalLicensePermission->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', 'application_documents', 'no_dues_documents']);
            $data = $this->curlAPiService->sendPostRequestInObject($newData, config('rtsapiurl.trade') . 'SHELMicroService/SHELApi/ApleSarkarService/UpdateForRenewTradeLicensePermission', '');

            // Decode JSON string to PHP array
            Log::info($newData);
            $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()];
        }
    }
}
