<?php

namespace EasyRestaurantManager\Http\Controllers;

use EasyRestaurantManager\Http\Requests\StoreReservationRequest;
use EasyRestaurantManager\Http\Requests\StoreReservationRequestUpdate;
use EasyRestaurantManager\Resources\ReservationResource;
use EasyRestaurantManager\Services\ReservationHelper;
use EasyRestaurantManager\Services\Arr;
use WP_REST_Request;

class ReservationController
{

    public static function getAvailableTables(WP_REST_Request $request)
    {
        $reservation_date = $request->get_param('date');
        $reservation_time = $request->get_param('time');

        if (!$reservation_date || !$reservation_time) {
            return rest_ensure_response([
                'message' => 'Reservation date and time are required.',
            ], 400);
        }
        $res = ReservationResource::getAvailableTables($reservation_date, $reservation_time);

        return rest_ensure_response([
            'message' => 'Available tables retrieved successfully',
            'tables' => $res,
        ]);
    }

    public static function postReservation(WP_REST_Request $request)
    {
        $reservationDuration = $request['reservation_duration'];

        $validatedRequest = new StoreReservationRequest($request);

        if ($validatedRequest->fails()) {
            return rest_ensure_response([
                'message' => 'Validation failed',
                'errors'  => $validatedRequest->errors()
            ], 400);
        }

        $data = $validatedRequest->validated();

        $today = new \DateTime();
        $days = is_numeric($reservationDuration) ? (int) $reservationDuration : 10;
        $maxDate = (clone $today)->modify("+$days days");
        $reservationDate = new \DateTime($data['reservation_date']);

        // if ($reservationDate < $today || $reservationDate > $maxDate) {
        //     return rest_ensure_response([
        //         'message' => "Reservation date must be within the next {$days} days.",
        //     ], 400);
        // }
        $res = ReservationResource::store($data);

        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to create table'
            ], 500);
        }
        if (!empty($data['email'])) {
            self::sendReservationConfirmationEmail($data);
        }

        return rest_ensure_response([
            'message' => 'Table created successfully',
            'table_data' => $res
        ]);
    }


    public static function checkReservedTables(WP_REST_Request $request)
    {
        global $wpdb;

        $reservation_date = $request->get_param('reservation_date');
        $reservation_time = $request->get_param('reservation_time');

        // Get reserved tables for the selected date and time
        $reserved_tables = $wpdb->get_col($wpdb->prepare("
            SELECT table_id FROM {$wpdb->prefix}reservations
            WHERE reservation_date = %s AND reservation_time = %s AND status != 'cancelled'
        ", $reservation_date, $reservation_time));

        if (empty($reserved_tables)) {
            return rest_ensure_response([
                'message' => 'No reserved tables for the selected date and time.',
                'reserved_tables' => []
            ]);
        }
    }

    public static function getReservation()
    {
        $res = ReservationResource::getReservation();

        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to get reservation'
            ], 500);
        }
        return rest_ensure_response([
            'message' => 'Reservation get successfully',
            'reservations' => $res
        ]);
    }

    public static function updateReservationStatus(WP_REST_Request $request)
    {
        $id = $request->get_param('id');
        $status = $request->get_param('status');

        if (empty($id) || !is_numeric($id) || $id <= 0) {
            return  rest_ensure_response([
                'message' => 'Invalid or missing reservation ID'
            ], 400);
        }

        $allowed_statuses = ['pending', 'confirmed', 'cancelled'];
        if (empty($status) || !in_array($status, $allowed_statuses)) {
            return rest_ensure_response([
                'message' => 'Invalid or missing reservation status'
            ], 400);
        }

        $res = ReservationResource::UpdateReservation($id, $status);

        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to update table'
            ], 500);
        }
        return rest_ensure_response([
            'message' => 'Table update successfully',
            'table_data' => $res
        ]);
    }

    public static function deleteReservation(WP_REST_Request $request)
    {
        $id = $request->get_param('id');
        if (!$id) {
            return rest_ensure_response([
                'message' => 'reservation table id is required'
            ], 400);
        }
        $res = ReservationResource::deleteReservation($id);

        if (!$res) {
            return rest_ensure_response([
                'message' => 'Failed to delete reservation table'
            ], 500);
        }
        return rest_ensure_response([
            'message' => 'Reservation Table deleted successfully'
        ]);
    }


    public static function sendReservationConfirmationEmail($data)
    {
        if (empty($data['email'])) {
            return;
        }

        $customerEmail = sanitize_email($data['email']);
        $customerName  = esc_html($data['customer_name']);
        $reservationDate = esc_html($data['reservation_date']);
        $reservationTime = esc_html($data['reservation_time']);
        $table_id = esc_html($data['table_id']);
        $phone = esc_html($data['phone']);
        $num_guests = esc_html($data['num_guests']);
    
        // Get settings
        $settings = get_option('easy_restaurant_manager_menus_template_settings');

        //  Stop if confirmation emails are disabled
        if (Arr::get($settings, 'confirmation_email') !== 'yes') {
            return;
        }
    
        $headers = ['Content-Type: text/html; charset=UTF-8'];
        //Send Email to Customer (if enabled)
        if (Arr::get($settings, 'customer_notification_email') === 'yes') {
            $customerSubject = Arr::get($settings, 'customer_subject');
            $customerSubject = ReservationHelper::parsePlaceholders($customerSubject, $data);
            $description = Arr::get($settings, 'customer_description');
            $description = ReservationHelper::parsePlaceholders($description, $data);
            // Process shortcodes
            $customerMessage = do_shortcode($description);
            wp_mail($customerEmail, $customerSubject, $customerMessage, $headers);
        }
    
        // Send Email to Admin (if enabled)
        if (Arr::get($settings, 'admin_notification_email') === 'yes') {
            $adminEmail = Arr::get($settings, 'admin_email');
            $adminSubject = Arr::get($settings, 'admin_subject');
    
            $adminSubject = ReservationHelper::parsePlaceholders($adminSubject, $data);
            $adminMessage = Arr::get($settings, 'admin_description');
            $adminMessage = ReservationHelper::parsePlaceholders($adminMessage, $data);

            wp_mail($adminEmail, $adminSubject, $adminMessage, $headers);
        }
    }
}
