<?php

namespace Alexr\Http\Traits;

use Alexr\Enums\BookingStatus;
use Alexr\Models\Booking;
use Alexr\Models\WhatsappConversation;
use Evavel\Eva;
use Evavel\Http\Request\Request;
use Evavel\Query\Query;

trait WhatsappInboxTrait_OLD
{
	/**
	 * Get bookings list with WhatsApp conversation data for the inbox
	 *
	 * @param Request $request
	 * @return \WP_REST_Response
	 */
	public function getInboxBookings(Request $request)
	{
		/*$user = Eva::make('user');
		if (!$user->canManage($request->tenant)) {
			return $this->response([
				'success' => false,
				'error' => __eva("You cannot access.")
			]);
		}*/

		$tenantId = $request->tenantId();
		$restaurant = \Alexr\Models\Restaurant::find($tenantId);
		$timezone = $restaurant->timezone ?? 'UTC';

		$dateRange = $request->date_range ?? 'today';
		$status = $request->status ?? 'all';
		$onlyUnread = $request->only_unread ?? false;

		/*ray([
			'date_range' => $dateRange,
			'status' => $status,
			'only_unread' => $onlyUnread
		]);*/

		// Build the base query
		$query = Booking::where('restaurant_id', $tenantId)
		                ->where('status', '!=', BookingStatus::SELECTED)
		                ->where('status', '!=', BookingStatus::DELETED);

		// Apply date range filter
		$dateNow = evavel_now_timezone_formatted($timezone, 'Y-m-d');
		//ray('dateNow:'.$dateNow);

		switch ($dateRange) {
			case 'today':
				$query->where('date', $dateNow);
				break;

			case 'tomorrow':
				$dateTomorrow = evavel_now_timezone($timezone)->modify('+1 day')->format('Y-m-d');
				$query->where('date', $dateTomorrow);
				break;

			case 'week':
				$dateEndWeek = evavel_now_timezone($timezone)->modify('+7 days')->format('Y-m-d');
				$query->where('date', '>=', $dateNow)
				      ->where('date', '<=', $dateEndWeek);
				break;

			case 'past':
				$query->where('date', '<', $dateNow);
				$query->orderBy('date', 'DESC');
				break;

			case 'all':
			default:
				$datePast = evavel_now_timezone($timezone)->modify('-7 days')->format('Y-m-d');
				$query->where('date', '>=', $datePast);
				break;
		}

		// Apply status filter
		if ($status !== 'all') {
			$query->where('status', $status);
		}

		// Order by date and time
		if ($dateRange !== 'past') {
			$query->orderBy('date', 'ASC'); //->orderBy('time', 'ASC');
		}

		// Limit results
		//$bookings = $query->limit(100)->get();
		//Query::setDebug(true);
		$bookings = $query->get();
		//Query::setDebug(false);

		// Get all booking IDs to fetch conversations in batch
		$bookingIds = [];
		foreach ($bookings as $booking) {
			$bookingIds[] = $booking->id;
		}

		// Fetch conversations for these bookings
		$conversations = [];
		if (!empty($bookingIds)) {
			$convQuery = WhatsappConversation::where('restaurant_id', $tenantId);

			// Fetch conversations for each booking
			foreach ($bookingIds as $bid) {
				$conv = WhatsappConversation::where('restaurant_id', $tenantId)
				                            ->where('booking_id', $bid)
				                            ->first();
				if ($conv) {
					$conversations[$bid] = $conv;
				}
			}
		}

		// Build response data
		$bookingsData = [];
		$totalUnread = 0;

		foreach ($bookings as $booking) {
			$conv = $conversations[$booking->id] ?? null;
			$unreadCount = $conv ? (int) $conv->unread_count : 0;
			$totalUnread += $unreadCount;

			$bookingItem = [
				'id' => $booking->id,
				'first_name' => $booking->first_name,
				'last_name' => $booking->last_name,
				'name' => ($booking->first_name ?? '') . ' ' . ($booking->last_name ?? ''),
				'phone' => $booking->phone,
				'dial_code' => $booking->dial_code,
				'email' => $booking->email,
				'date' => $booking->date,
				'time' => $booking->time,
				'party' => $booking->party,
				'status' => $booking->status,
				'tablesList' => $booking->tablesList ?? null,

				// Conversation data
				'has_conversation' => $conv !== null,
				'unread_count' => $unreadCount,
				'last_message_at' => $conv ? $conv->last_message_at : null,
				'window_open' => $conv ? $conv->isWindowOpen : false,
				'window_expires_at' => $conv ? $conv->window_expires_at : null,
				'message_count' => $conv ? (int) $conv->message_count : 0,
			];

			$bookingsData[] = $bookingItem;
		}

		// If only_unread filter is active, filter on PHP side
		if ($onlyUnread) {
			$bookingsData = array_values(array_filter($bookingsData, function ($b) {
				return $b['unread_count'] > 0;
			}));
		}

		// Sort: unread first, then by date/time
		usort($bookingsData, function ($a, $b) {
			// Unread first
			if ($a['unread_count'] > 0 && $b['unread_count'] === 0) return -1;
			if ($b['unread_count'] > 0 && $a['unread_count'] === 0) return 1;

			// Then by date
			$dateCompare = strcmp($a['date'], $b['date']);
			if ($dateCompare !== 0) return $dateCompare;

			// Then by time
			return ($a['time'] ?? 0) - ($b['time'] ?? 0);
		});

		return $this->response([
			'success' => true,
			'data' => [
				'bookings' => $bookingsData,
				'total_unread' => $totalUnread,
			]
		]);
	}

	/**
	 * Get total unread count across all bookings (lightweight endpoint for polling badge)
	 *
	 * @param Request $request
	 * @return \WP_REST_Response
	 */
	public function getInboxUnreadCount(Request $request)
	{
		$user = Eva::make('user');
		if (!$user->canManage($request->tenant)) {
			return $this->response([
				'success' => false,
				'error' => __eva("You cannot access.")
			]);
		}

		$tenantId = $request->tenantId();

		$totalUnread = 0;
		$unreadConversations = WhatsappConversation::where('restaurant_id', $tenantId)
		                                           ->where('unread_count', '>', 0)
		                                           ->get();

		foreach ($unreadConversations as $conv) {
			$totalUnread += (int) $conv->unread_count;
		}

		return $this->response([
			'success' => true,
			'data' => [
				'total_unread' => $totalUnread,
			]
		]);
	}
}
