<?php

if (!class_exists('Enum')) {
    include(__DIR__ . '/../config/enum.php');
}

class Config
{
}

$basePath = (strpos($_SERVER['REQUEST_URI'], '/booking_accounting/') !== false) ? '/booking_accounting' : '';

$realPath = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http")
    . "://"
    . $_SERVER['HTTP_HOST']
    . $basePath
    . '/';

define('BASE_URL', $realPath);

$user_status = [
    0 => 'DE-ACTIVE',
    1 => 'ACTIVE'
];

$currentMonth = date('n'); // Current month (1 to 12)
$currentYear = date("Y");

$daysNameShort = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
$daysNameFull = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
$monthsNameShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
$monthsNameFull = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

$permissionMsg = "You don't have permission to access.";

function sCurrencySymbol($beforSpace = true, $afterSpace = true, $symble = true)
{
    // $symble = '&#2547;';
    $symble = $symble ? '&#2547;' : 'tk.';
    $currencySymble = $symble;
    if ($beforSpace) {
        $currencySymble = "&nbsp;" . $currencySymble;
    }
    if ($afterSpace) {
        $currencySymble = $currencySymble . "&nbsp;";
    }
    return $currencySymble;
}

function sDate($date, $daysName = false, $time = false, $use12HourFormat = true, $hideSecond = true)
{
    global $daysNameShort, $monthsNameShort;

    if ($date instanceof DateTime) {
        $formattedDate = $date;
    } else {
        $formattedDate = new DateTime($date);
    }

    $dayName = $daysNameShort[$formattedDate->format('w')];
    $day = $formattedDate->format('d');
    $monthName = $monthsNameShort[$formattedDate->format('m') - 1];
    $year = $formattedDate->format('Y');

    $result = "{$day}-{$monthName}-{$year}";

    if ($daysName) {
        $result = "{$dayName}, {$day}-{$monthName}-{$year}";
    }

    $result = $result . ($time ? ' ' . sTime($date, $use12HourFormat, $hideSecond) : '');
    return $result;
}

function sTime($date, $use12HourFormat = true, $hideSecond = true)
{
    if ($date instanceof DateTime) {
        $formattedDate = $date;
    } else {
        $formattedDate = new DateTime($date);
    }

    $hours = (int) $formattedDate->format('H');
    $minutes = $formattedDate->format('i');
    $seconds = $formattedDate->format('s');

    $period = '';
    if ($use12HourFormat) {
        $period = ($hours >= 12) ? ' PM' : ' AM';
        $hours = $hours % 12;
        if ($hours == 0) {
            $hours = 12;
        }
        $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
    } else {
        $hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
    }

    return "{$hours}:{$minutes}" . ($hideSecond ? '' : ":{$seconds}") . "{$period}";
}

function eventDuration($date, $eventId, $packageId): string
{
    if ($date instanceof DateTime) {
        $start = $date;
    } else {
        $start = new DateTime($date);
    }

    $end = clone $start;
    if ($packageId == "14") {
        $end->modify('+2 hours');
    }else{
        $end->modify('+5 hours');
    }

    return sTime($start) . ' - ' . sTime($end);
}

function AdditionalTimeArr($input, $onlyValue = false)
{
    if (empty($input))
        return [];

    $parts = explode('|', $input);

    if (count($parts) !== 2) {
        return [];
    }

    $hours = $parts[0];
    $amount = $parts[1];

    $hoursLabel = ((int) $hours > 1) ? $hours . ' Hours' : $hours . ' Hour';
    $hoursLabel = ($onlyValue) ? $hours : $hoursLabel;

    return [
        'hours' => $hoursLabel,
        'amount' => $amount
    ];
}

function AddOnsArr($input)
{
    if (empty($input))
        return [];

    $result = [];
    $items = explode(',', $input);

    foreach ($items as $item) {
        $parts = explode('|', $item);
        if (count($parts) !== 2)
            continue;

        $result[] = [
            'name' => trim($parts[0]),
            'amount' => trim($parts[1])
        ];
    }

    return $result;
}

function PackageArr($input)
{
    if (empty($input))
        return [];

    $result = [];
    $items = explode(',', $input);

    foreach ($items as $item) {
        $parts = explode('|', $item);
        if (count($parts) !== 2)
            continue;

        $result[] = [
            'title' => trim($parts[0]),
            'details' => trim($parts[1])
        ];
    }

    return $result;
}

function sTakaFormat($amount, $paisa = false, $symble = false, $beforSpace = true, $afterSpace = true)
{
    $sign = $amount < 0 ? "-" : "";
    $amount = abs($amount);
    $amount = number_format($amount, 2, '.', '');
    $parts = explode('.', $amount);
    $number = $parts[0];
    $decimal = isset($parts[1]) ? '.' . $parts[1] : '';

    $len = strlen($number);
    if ($len > 3) {
        $last3 = substr($number, -3);
        $restUnits = substr($number, 0, $len - 3);
        $restUnits = preg_replace("/\B(?=(\d{2})+(?!\d))/", ",", $restUnits);
        $formatted = $restUnits . ',' . $last3;
    } else {
        $formatted = $number;
    }

    $result = $paisa ? $formatted . $decimal : $formatted;

    return $sign . ($symble ? sCurrencySymbol($beforSpace, $afterSpace) : '') . $result;
}

function sNumberToWords($number)
{
    $words = array(
        '0' => 'zero',
        '1' => 'one',
        '2' => 'two',
        '3' => 'three',
        '4' => 'four',
        '5' => 'five',
        '6' => 'six',
        '7' => 'seven',
        '8' => 'eight',
        '9' => 'nine',
        '10' => 'ten',
        '11' => 'eleven',
        '12' => 'twelve',
        '13' => 'thirteen',
        '14' => 'fourteen',
        '15' => 'fifteen',
        '16' => 'sixteen',
        '17' => 'seventeen',
        '18' => 'eighteen',
        '19' => 'nineteen',
        '20' => 'twenty',
        '30' => 'thirty',
        '40' => 'forty',
        '50' => 'fifty',
        '60' => 'sixty',
        '70' => 'seventy',
        '80' => 'eighty',
        '90' => 'ninety'
    );

    $digits = array('', 'hundred', 'thousand', 'lakh', 'crore');

    if (!is_numeric($number))
        return false;

    $number = number_format($number, 2, '.', '');
    $parts = explode('.', $number);
    $no = (int) $parts[0];
    $point = isset($parts[1]) ? (int) $parts[1] : 0;

    $str = array();
    $digits_1 = strlen($no);
    $i = 0;

    $divider = [10000000, 100000, 1000, 100, 1];
    $words_order = ['crore', 'lakh', 'thousand', 'hundred', ''];

    foreach ($divider as $idx => $value) {
        $quotient = intval($no / $value);
        $no = $no % $value;

        if ($quotient) {
            if ($quotient < 21) {
                $str[] = $words[$quotient] . ' ' . $words_order[$idx];
            } else {
                $tens = intval($quotient / 10) * 10;
                $unit = $quotient % 10;
                $str[] = $words[$tens] . ' ' . ($unit ? $words[$unit] : '') . ' ' . $words_order[$idx];
            }
        }
    }

    $taka = implode(' ', array_filter($str));

    $paisa = '';
    if ($point) {
        if ($point < 21) {
            $paisa = $words[$point];
        } else {
            $tens = intval($point / 10) * 10;
            $unit = $point % 10;
            $paisa = $words[$tens] . ' ' . ($unit ? $words[$unit] : '');
        }
    }

    if (empty($taka)) {
        $taka = 'zero';
    }

    $result = ucwords($taka);
    if ($paisa) {
        $result .= ' and ' . ucwords($paisa) . ' Paisa';
    }
    $result .= ' Taka Only';

    return $result;
}

function EventFieldShow(int $eventTypeId = 0, int $packageId = 0, string $fieldName){
    $flag = false;
    if (
        $eventTypeId == 1 ||   // Wedding
        $eventTypeId == 2 ||   // Reception
        $eventTypeId == 3 ||   // Engagement
        $eventTypeId == 4 ||   // Halud
        $eventTypeId == 5 ||   // Mehadi
        $eventTypeId == 6 ||   // Akhd
        $eventTypeId == 7 ||   // Anniversary
        $eventTypeId == 8 ||   // Rong Khela
        $eventTypeId == 9 ||   // Ashirbad
        $eventTypeId == 14      // Dala
    ) {
        $flag = ($fieldName == 'event_type' || $fieldName == 'grom_name' || $fieldName == 'bride_name' || $fieldName == 'package_name' || $fieldName == 'add_ons');
    } else if ($eventTypeId == 10) { // Birthday
        $flag = ($fieldName == 'birthday_person_name' || $fieldName == 'add_ons');
    } else if (
        $eventTypeId == 11 ||  // Architectural
        $eventTypeId == 12     // Corporate
    ) {
        $flag = ($fieldName == 'event_type' || $fieldName == 'org_name');
    } else if ($eventTypeId == 13) { // Fashion & Lifetyle
        //
    }

    if (
        $packageId == 1 ||   // Standard - I
        $packageId == 2 ||   // Standard - II
        $packageId == 3 ||   // Standard - III
        $packageId == 4 ||   // Premium - I
        $packageId == 5 ||   // Premium - II
        $packageId == 6 ||   // Premium - III
        $packageId == 7 ||   // Elite - I
        $packageId == 8 ||   // Elite - II
        $packageId == 9 ||   // Sonaton - Standrad
        $packageId == 10 ||  // Sonaton - Premium
        $packageId == 11 ||  // Only Photography
        $packageId == 12 ||  // Only Photography - Premium
        $packageId == 14     // Quick Look
    ) {
        // $song = $this->SanitizeString($songPreference);
        // $preference = $yourPreference;
    } else if ($packageId == 13) { // Other
        // $amount = $amountTk;
        // $preference = $yourPreference;
    }

    return $flag;
}

function sImageToBase64(string $imagePath)
{
    if (!file_exists($imagePath)) {
        return null;
    }

    $imageData = file_get_contents($imagePath);
    if ($imageData === false) {
        return null;
    }

    $base64 = base64_encode($imageData);
    $extension = pathinfo($imagePath, PATHINFO_EXTENSION);

    return 'data:image/' . $extension . ';base64,' . $base64;
}

function GetClientIP()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

function GetCountryByIP($ip, $return = "country")
{
    $url = "https://ipwho.is/" . $ip;

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);

    $result = curl_exec($ch);
    curl_close($ch);

    if (!$result) {
        return "Unknown";
    }

    $data = json_decode($result, true);
    return $data[strtolower($return)] ?? 'Unknown';
}

function GetBrowserName()
{
    $ua = $_SERVER['HTTP_USER_AGENT'];

    if (strpos($ua, 'Firefox') !== false)
        return 'Firefox';
    if (strpos($ua, 'Chrome') !== false)
        return 'Chrome';
    if (strpos($ua, 'Safari') !== false)
        return 'Safari';
    if (strpos($ua, 'Edge') !== false)
        return 'Edge';
    if (strpos($ua, 'Opera') !== false || strpos($ua, 'OPR') !== false)
        return 'Opera';
    return 'Unknown';
}