<?php

namespace App\Helpers;

use Carbon\Carbon;

class TimezoneHelper
{
    /**
     * Get timezone based on country ID
     */
    public static function getTimezoneByCountry($countryId)
    {
        $timezones = [
            1 => 'Asia/Tehran',        // Iran
            2 => 'Asia/Shanghai',      // China
            3 => 'Europe/Paris',       // France
            4 => 'America/New_York',   // USA
            5 => 'Europe/London',      // UK
            6 => 'Asia/Tokyo',         // Japan
            7 => 'Australia/Sydney',   // Australia
            8 => 'Europe/Berlin',      // Germany
            9 => 'Asia/Dubai',         // UAE
            10 => 'Asia/Riyadh',       // Saudi Arabia
            // Add more countries as needed
        ];

        return $timezones[$countryId] ?? 'Asia/Tehran'; // Default to Iran
    }

    /**
     * Get current time in location's timezone
     */
    public static function getCurrentTimeForLocation($location)
    {
        $timezone = self::getTimezoneByCountry($location->country_id ?? 1);
        return Carbon::now($timezone);
    }

    /**
     * Check if location is currently open
     */
    public static function isLocationOpen($location)
    {
        if (!$location->open_hours || !$location->closing_hours) {
            return true; // Default to open if no hours specified
        }

        $now = self::getCurrentTimeForLocation($location);
        
        // Convert Persian numbers to English
        $openTime = str_replace(['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'], ['0','1','2','3','4','5','6','7','8','9'], $location->open_hours);
        $closeTime = str_replace(['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'], ['0','1','2','3','4','5','6','7','8','9'], $location->closing_hours);
        
        // Parse time in various formats
        $openHour = null;
        $openMinute = 0;
        $closeHour = null;
        $closeMinute = 0;
        
        // Extract hour and minute from open time
        if(preg_match('/(\d{1,2})(?::(\d{1,2}))?/', $openTime, $openMatches)) {
            $openHour = (int)$openMatches[1];
            $openMinute = isset($openMatches[2]) ? (int)$openMatches[2] : 0;
        }
        
        // Extract hour and minute from close time
        if(preg_match('/(\d{1,2})(?::(\d{1,2}))?/', $closeTime, $closeMatches)) {
            $closeHour = (int)$closeMatches[1];
            $closeMinute = isset($closeMatches[2]) ? (int)$closeMatches[2] : 0;
        }
        
        if($openHour === null || $closeHour === null) {
            return true; // Default to open if parsing fails
        }
        
        $currentHour = (int)$now->format('H');
        $currentMinute = (int)$now->format('i');
        
        // Convert to total minutes for accurate comparison
        $currentTotalMinutes = $currentHour * 60 + $currentMinute;
        $openTotalMinutes = $openHour * 60 + $openMinute;
        $closeTotalMinutes = $closeHour * 60 + $closeMinute;
        
        // Check if currently open
        if($closeTotalMinutes < $openTotalMinutes) {
            // Overnight hours (e.g., 22:00 to 06:00)
            return ($currentTotalMinutes >= $openTotalMinutes) || ($currentTotalMinutes < $closeTotalMinutes);
        } else {
            // Normal hours (e.g., 07:00 to 22:00)
            return ($currentTotalMinutes >= $openTotalMinutes) && ($currentTotalMinutes < $closeTotalMinutes);
        }
    }

    /**
     * Get status text and class for location
     */
    public static function getLocationStatus($location)
    {
        $isOpen = self::isLocationOpen($location);
        
        return [
            'isOpen' => $isOpen,
            'statusText' => $isOpen ? 'باز' : 'بسته',
            'statusClass' => $isOpen ? 'open' : 'closed',
            'timezone' => self::getTimezoneByCountry($location->country_id ?? 1),
            'currentTime' => self::getCurrentTimeForLocation($location)
        ];
    }
}
