<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PaymentMethods;
use App\Models\Currencies;
use App\Models\User;
use App\Models\Payments;
use App\Helper\Helper;
use Illuminate\Support\Facades\Session;
use App\Exports\PaymentExport;
use Maatwebsite\Excel\Facades\Excel;

class PaymentsController extends Controller
{

    
    
    /**
     * 
     */
    public function create(Request $request){
        try {
            $thereCurrencies = (count(Currencies::all()) > 0);
            $therePaymentsMethods = (count(PaymentMethods::all()) > 0) ;;

            if($thereCurrencies && $therePaymentsMethods){ 
                $payment = new Payments();
                $currencies = Currencies::all();
                $paymentMethods = PaymentMethods::all();
                $doctors = User::getAllDoctors();
                $data = $request->all();
                if(($request->method() === "POST")){
                    $payment->id = Helper::createId();
                    $payment->especiality_id = $data["especiality"];
                    $payment->users_id = $data["doctors"];
                    $payment->payment_methods_id = $data["paymentMethods"];
                    $payment->currencies_id  = $data["currency"];
                    $payment->address_payer = $data["address_payer"];
                    $payment->amount = $data["amount"];
                    
                    // Manejar pago electrónico
                    $payment->is_electronic = isset($data["is_electronic"]) ? true : false;
                    
                    // Si es pago electrónico, usar referencia proporcionada por el usuario
                    if ($payment->is_electronic && isset($data["user_reference"])) {
                        $payment->user_reference = $data["user_reference"];
                        $payment->reference = $data["user_reference"]; // Usar la misma referencia
                    } else {
                        // Si no es electrónico, generar referencia automática
                        $payment->reference = substr(Helper::createReferenceForPayments($payment->users_id,$payment->amount), 0, 255);
                    }
                    
                    $payment->description = $data["reason"];
                    $payment->payer = $data["payer"];
                    if($payment->save()){
                        return redirect()->route('/admin/detail-payment', ['id' => $payment->id]);
                    }
                }
                 return view("create-payment",[
                    "currencies"=>$currencies,
                    "paymentMethods"=>$paymentMethods,
                    "doctors"=>$doctors,
                    "payment"=>$payment
                 ]);
            }else if(!$thereCurrencies){
                Session::flash('message', __("create-payment.ThereNotCurrency"));
                return view('create-currency',["redirectToCreatePayment"=>"true"]);
            }else if(!$therePaymentsMethods){
                Session::flash('message',  __("create-payment.ThereNotPaymentMethod"));
                return view('create-payments-method',["redirectToCreatePayment"=>"true"]);
            }

           
        } catch (Throwable $th) {
            throw new GlobalException(__($th->getMessage()));
        }
    }


     /**
     * 
     */
    public function view(Request $request){
        try{
             $data = $request->all();
             $payment = new Payments();
             return view("view-payments",[
                "payments"=>$payment::where('active', 1)->get()
             ]);
        }catch (Throwable $th) {
             throw new GlobalException($th->getMessage());
         }
     }
 
     /**
      * 
      */
     public function detail(Request $request){
        try {
            $data = $request->all();
            $id = $data["id"];
            
            // Cargar el pago principal con sus relaciones
            $model = Payments::with([
                'currency',
                'paymentMethod',
                'especiality',
                'user.profile',
                'children' => function($query) {
                    $query->with([
                        'currency',
                        'paymentMethod',
                        'user.profile'
                    ])->orderBy('created_at', 'desc');
                }
            ])->find($id);
            
            if ($model === null) {
                throw new GlobalException(__("error-500.messageNoSearch"));
            }
            
            return view("detail-payment", [
                "model" => $model,
                "childPayments" => $model->children ?? collect()
            ]);
            
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
     }


     
    /**
     * 
     */
    public function update(Request $request){
        try{
         $data = $request->all();
         return view("detail-payment");
        }catch (Throwable $th) {
             throw new GlobalException($th->getMessage());
         }
     }

    /**
     * Display the specified payment.
     *
     * @param  string  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $payment = Payments::with(['especiality', 'paymentMethod', 'currency', 'user', 'medicalServices'])->findOrFail($id);
        
        return view('detail-payment', [
            'model' => $payment,
            'title' => __('view-payments.paymentDetails')
        ]);
    }

    /**
     * Export payments to Excel
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function export(Request $request)
    {
        try {
            $filename = 'pagos_' . date('Y-m-d') . '.xlsx';
            return Excel::download(new PaymentExport(), $filename);
        } catch (Throwable $th) {
            throw new GlobalException($th->getMessage());
        }
    }
}
