<?php

namespace Bot;

require_once __DIR__ . "/../config/jdf.php";

use Config\jdf;

class DatePicker
{

    private $jalaliMonths = [
        1 => 'فروردین',
        2 => 'اردیبهشت',
        3 => 'خرداد',
        4 => 'تیر',
        5 => 'مرداد',
        6 => 'شهریور',
        7 => 'مهر',
        8 => 'آبان',
        9 => 'آذر',
        10 => 'دی',
        11 => 'بهمن',
        12 => 'اسفند'
    ];

    /**
     * کیبورد انتخابگر تاریخ را تولید می‌کند
     */

    public function generate($year = null, $month = null, $day = null, $prefix = 'datepicker', $headerText = null)
    {

        // اگر تاریخ ورودی نداشتیم یا نامعتبر بود، از تاریخ امروز استفاده کن
        if (empty($year) || empty($month) || empty($day)) {
            $year = (int)jdf::jdate('Y');
            $month = (int)jdf::jdate('n');
            $day = (int)jdf::jdate('j');
        }

        if ($year == 0 || $month == 0 ||  $day == 0) {
            $year = 1404;
            $month = 4;
            $day = 15;
        }

        $text = "";
        if ($headerText) {
            $text .= $headerText . "\n\n"; // نمایش هدر (خلاصه تور)
        }
        $text .= "<b>تاریخ انتخاب شده:</b> <code>$year/$month/$day</code>";

        $reply_markup = [
            'inline_keyboard' => $this->generateKeyboard($year, $month, $day, $prefix)
        ];

        return [
            'text' => $text,
            'reply_markup' => json_encode($reply_markup)
        ];
    }

    /**
     * کیبورد انتخابگر ساعت را تولید می‌کند
     */
    public function generateTimePicker($hour = 12, $minute = 0, $prefix = 'timepicker', $headerText = null)
    {
        $text = "";
        if ($headerText) {
            $text .= $headerText . "\n\n";
        }
        $text .= "<b>ساعت انتخاب شده:</b> <code>" . sprintf('%02d:%02d', $hour, $minute) . "</code>";

        $keyboard = [
            [
                ['text' => '▼', 'callback_data' => "{$prefix}-hour_decr-{$hour}-{$minute}"],
                ['text' => "ساعت: $hour", 'callback_data' => "{$prefix}-noop"],
                ['text' => '▲', 'callback_data' => "{$prefix}-hour_incr-{$hour}-{$minute}"]
            ],
            [
                ['text' => '▼', 'callback_data' => "{$prefix}-min_decr-{$hour}-{$minute}"],
                ['text' => "دقیقه: $minute", 'callback_data' => "{$prefix}-noop"],
                ['text' => '▲', 'callback_data' => "{$prefix}-min_incr-{$hour}-{$minute}"]
            ],
            [
                ['text' => '✔️ ثبت ساعت', 'callback_data' => "{$prefix}-confirm-{$hour}-{$minute}"]
            ]
        ];
        $keyboard[] = [['text' => '🔙 بازگشت', 'callback_data' => "{$prefix}-back-{$hour}-{$minute}"]];



        return [
            'text' => $text,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }

    /**
     * پاسخ‌های مربوط به انتخابگر تاریخ را پردازش می‌کند
     */
    public function handleCallback($callbackData)
    {
        $parts = explode('-', $callbackData);
        $prefix = $parts[0];
        $action = $parts[1];
        $year = (int)$parts[2];
        $month = (int)$parts[3];
        $day = (int)$parts[4];

        if (str_starts_with($action, 'year_')) {
            $year += ($action === 'year_incr' ? 1 : -1);
        } elseif (str_starts_with($action, 'set_month_')) {
            $month = (int)str_replace('set_month_', '', $action);
        } elseif (str_starts_with($action, 'set_day_')) {
            $day = (int)str_replace('set_day_', '', $action);
        } elseif ($action === 'confirm') {
            return [
                'status' => 'confirmed',
                'date' => ['year' => $year, 'month' => $month, 'day' => $day]
            ];
        } elseif ($action === 'noop') {
            return ['status' => 'noop'];
        }
        elseif ($action === 'back') {
            return ['status' => 'back'];
        }


        return [
            'status' => 'update',
            'new_data' => $this->generate($year, $month, $day, $prefix)
        ];
    }

    /**
     * پاسخ‌های مربوط به انتخابگر ساعت را پردازش می‌کند
     */
    public function handleTimeCallback($callbackData)
    {
        $parts = explode('-', $callbackData);
        $prefix = $parts[0];
        $action = $parts[1];
        $hour = (int)$parts[2];
        $minute = (int)$parts[3];

        if ($action === 'hour_incr') $hour = ($hour + 1) % 24;
        elseif ($action === 'hour_decr') $hour = ($hour - 1 + 24) % 24;
        elseif ($action === 'min_incr') $minute = ($minute + 15) % 60;
        elseif ($action === 'min_decr') $minute = ($minute - 15 + 60) % 60;
        elseif ($action === 'confirm') {
            return [
                'status' => 'confirmed',
                'time' => sprintf('%02d:%02d', $hour, $minute)
            ];
        } elseif ($action === 'noop') {
            return ['status' => 'noop'];
        }
        elseif ($action === 'back') {
            return ['status' => 'back'];
        }

        return [
            'status' => 'update',
            'new_data' => $this->generateTimePicker($hour, $minute, $prefix)
        ];
    }

    private function generateKeyboard($year, $month, $day, $prefix)
    {

        $keyboard = [];
        $keyboard[] = [
            ['text' => '▼', 'callback_data' => "{$prefix}-year_decr-{$year}-{$month}-{$day}"],
            ['text' => "سال: $year", 'callback_data' => "{$prefix}-noop"],
            ['text' => '▲', 'callback_data' => "{$prefix}-year_incr-{$year}-{$month}-{$day}"]
        ];

        $monthButtons = [];
        foreach ($this->jalaliMonths as $num => $name) {
            $monthButtons[] = ['text' => ($num == $month ? '✅ ' : '') . $name, 'callback_data' => "{$prefix}-set_month_{$num}-{$year}-{$month}-{$day}"];
        }
        $keyboard = array_merge($keyboard, array_chunk($monthButtons, 3));

        $dayButtons = [];
        // استفاده از تابع صحیح jmaketime از jdf.php یا جایگزین آن
        if (!function_exists('jmaketime')) {
            function jmaketime($hour, $minute, $second, $month, $day, $year)
            {
                // اگر jmaketime در jdf.php تعریف نشده بود، این نسخه ساده را استفاده کن
                return mktime($hour, $minute, $second, $month, $day, $year);
            }
        }

        $daysInMonth = ($month < 7) ? 31 : (($month < 12) ? 30 : (jdf::jdate('L', jmaketime(0, 0, 0, $month, 1, $year)) ? 30 : 29));
        for ($d = 1; $d <= $daysInMonth; $d++) {
            $dayButtons[] = ['text' => ($d == $day ? '✅' : '') . $d, 'callback_data' => "{$prefix}-set_day_{$d}-{$year}-{$month}-{$day}"];
        }
        $keyboard = array_merge($keyboard, array_chunk($dayButtons, 7));

        $keyboard[] = [['text' => '✔️ ثبت تاریخ', 'callback_data' => "{$prefix}-confirm-{$year}-{$month}-{$day}"]];
        $keyboard[] = [['text' => '🔙 بازگشت', 'callback_data' => "{$prefix}-back-{$year}-{$month}-{$day}"]];


        return $keyboard;
    }

}
