<?php

namespace App\Http\Controllers\Hotel;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Request;

use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Mail;
use App\Mail\Reservations\ReservationTicket;

use App\Models\Environment\Business;
use App\Models\Hotel\Reservation;
use App\Models\User;

use App\Helpers\Environment\SystemFeaturesHelper;
use App\Helpers\Support\PdfResourcesHelper;

class ReservationTicketsController extends Controller
{
  //* Constructor
    public function __construct() {
        $this->middleware(['auth']);
    }

  //* Basic CRUD
    // Reservation Details
    public function fullStayTickets() {
        if(request()->ajax()){
            $control_hours = SystemFeaturesHelper::getFeatureStatus("control_hours");
            $express_reservations = SystemFeaturesHelper::getFeatureStatus("express_reservations");

            return datatables()->of(Reservation::where('has_checkIn', 'Si')->where('has_checkOut', 'Si')->get())
                ->addColumn('num_room',function($data){
                    return $data->Room->room_name;
                })
                ->addColumn('check_in', function($data) use($control_hours, $express_reservations) {
                    return ($control_hours && $express_reservations)
                        ? "{$data->date_entry}<br>{$data->hour_entry}"
                        : $data->date_entry;
                })
                ->addColumn('checkout', function($data) use($control_hours, $express_reservations) {
                    return ($control_hours && $express_reservations)
                        ? "{$data->date_departure}<br>{$data->hour_departure}"
                        : $data->date_departure;
                })
                ->addColumn('length_of_stay', function($data) use($express_reservations){
                  // Dynamic Lang
                    $reservation_fields = __('entity_fields')['reservation'];

                  // Build Response
                    $nights = trans_choice($reservation_fields['dynamic_number_nights'], $data->number_nights);
                    $duration = "{$data->number_nights} {$nights}";

                        if ($express_reservations) {
                            $hours = trans_choice($reservation_fields['dynamic_number_hours'], $data->number_hours);
                            $duration .= ", {$data->number_hours} {$hours}";
                        }

                    return $duration;
                })
                ->addColumn('created_at', function($data){
                    return date("d-m-Y H:i:s", strtotime($data->created_at));
                })
                ->addColumn('action', function($data){
                    $url = route('reservation.tickets.fullStays.show', ['id' => $data->id]);
                    $button = '<a type="button" name="editar" class="px-2 editar btn btn-success btn-ms" href="'.$url.'" target="_blank"><i class="fa fa-eye"></i></a>';
                    return $button;
                })
                ->rawColumns(['action', 'num_room', 'check_in', 'checkout'])
                ->make(true);
        }

        return view('hotel.reservation-details.index');
    }

    public function showFullStay($id) {
        $hotel = Business::first();
        $reservation = Reservation::findOrFail($id);
        return view('hotel.reservation-details.show', compact(['reservation','hotel']));
    }

    public function sendFullStayTicket(Request $request, $id) {
      // Validate Request
        $request->validate([
            'email' => ['required','email:rfc'],
        ]);

      // Send Email
        try {
          // Get records
            $reservation = Reservation::findOrFail($id);
            $business = Business::first();

          // Update Client Email
            $reservation->client()->update(["client_email" => $request['email']]);

          // Send Email
            $from_address = config('mail.hotel_address') ?: config('mail.from.address');
            Mail::to($request['email'])->send(
                (new ReservationTicket($reservation, $business))->from($from_address)
            );

          // Response
            return response()->json([
                'success' => true,
                'message' => __('common_responses_and_messages')['email_sent_successfully'],
            ]);
        } catch (\Exception $e) {
            Log::error("Error al enviar ticket de reservación #$id: " . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => __('common_responses_and_messages')['email_not_sent'],
            ], 500);
        }
    }

    public function downloadFullStayTicket($id) {
      // Parameters
        $reservation = Reservation::findOrFail($id);
        $business    = Business::first();

      // Local Variables
        $paper_size = [0, 0, 435, 650];

        $logo_url = optional(User::first())->profile_photo;
        $fallback_url = public_path('images/harsi_logo.png');

      // Global Variables
        $pdf_name  = __('emails')['reservation_ticket']['title']." ".$reservation->id;
        $hotel_logo = PdfResourcesHelper::domPDFImageRender($logo_url, $fallback_url);

      // Control Variables
        $has_control_hours =  SystemFeaturesHelper::getFeatureStatus("control_hours");
        $has_express_reservations =  SystemFeaturesHelper::getFeatureStatus("express_reservations");
        $has_pax_pricing =  SystemFeaturesHelper::getFeatureStatus("pax_pricing");

      // Build Variables
        $pdf = Pdf::loadView('hotel.reservation-details.ticket-pdf', [
            'reservation' => $reservation,
            'business'    => $business,
            'display_signature' => true,
            'has_control_hours' => $has_control_hours,
            'has_express_reservations' => $has_express_reservations,
            'has_pax_pricing' => $has_pax_pricing,

            'title'       => $pdf_name,
            'logo_src'    => $hotel_logo,
        ])->setPaper($paper_size)->setOptions([
            'defaultFont' => 'sans-serif',
            'isHtml5ParserEnabled' => true,
            'isRemoteEnabled'      => false
        ]);

        return $pdf->download($pdf_name.'.pdf');
        // return $pdf->stream($pdf_name . '.pdf');
    }

    // Reservation Consumptions
    public function consumptionTickets() {
        if (request()->ajax()) {

            return datatables()->of(Reservation::where('has_checkIn', 'Si')->get())

                ->addColumn('consumption_charges', function ($data) {
                    $consumption = $data->consumptionCharges->where('status', 'Activo')->sum('consumption_price');
                    return number_format($consumption, 2, '.', '');
                })
                ->addColumn('consumption_payments', function ($data) {
                    $consumption = $data->consumptionPayments->where('status', 'Activo')->sum('payment_price');
                    return number_format($consumption, 2, '.', '');
                })

                ->addColumn('action', function($data){
                    $url = route('reservation.tickets.hotelConsumptions.show', ['id' => $data->id]);
                    $button = '<a type="button" name="editar" class="px-2 editar btn btn-success btn-ms" href="'.$url.'" target="_blank"><i class="fa fa-eye"></i></a>';
                    return $button;
                })

                ->make(true);
        }

        return view('hotel.reservation-consumptions.index');
    }

    public function showConsumptions($id) {
        $hotel = Business::first();
        $reservation = Reservation::findOrFail($id);
        return view('hotel.reservation-consumptions.show', compact(['reservation','hotel']));
    }
}
