<?php

if (!defined('ABSPATH')) {
    exit;
}

add_shortcode('bibldare_bible_reading_plan', function ($atts) {
    $admin_lang = get_option('bibldare_bible_language', 'eng');
    $admin_version = get_option('bibldare_bible_version', DEFAULT_VERSION);
    $admin_bg = get_option('bibldare_bible_background', 'white');
    $admin_tz = get_option('bibldare_bible_timezone', 'Asia/Tbilisi');
    $admin_custom_bg_color = get_option('bibldare_bible_custom_background_color', '');
    $admin_text_color = get_option('bibldare_bible_text_color', '');

    $atts = shortcode_atts([
        'lang' => $admin_lang,
        'version' => $admin_version,
        'background' => $admin_bg,
        'timezone' => $admin_tz,
        'custom_background_color' => $admin_custom_bg_color,
        'text_color' => $admin_text_color,
    ], $atts, 'bibldare_bible_reading_plan');

    $language = $atts['lang'];
    $version = $atts['version'];
    $background = $atts['background'];
    $timezone = $atts['timezone'];
    $custom_background_color = $atts['custom_background_color'];
    $text_color = $atts['text_color'];
    $day = bibldare_get_today_index($timezone);

    ob_start();
?>
    <div class="bible-schedule-wrapper">
        <div class="bible-header bible-schedule-navigation"><?php
                                                            $bgClass = 'bible-bg-' . $background;
                                                            $formattedDate = bibldare_get_formatted_georgian_date($day, $language, $timezone);
                                                            ?><div class="bible-nav-arrows">
                <div id="prev-day" data-day="<?php echo esc_attr($day); ?>" class="bible-nav-button <?php echo esc_attr($bgClass); ?>" aria-label="Previous day" style="<?php if (!empty($custom_background_color)) echo 'background-color: ' . esc_attr($custom_background_color) . ';'; ?>
        <?php if (!empty($text_color)) echo 'color: ' . esc_attr($text_color) . ';' ?>"><?php include plugin_dir_path(__FILE__) . '../assets/icons/left-arrow-icon.php'; ?></div>
                <div id="next-day" data-day="<?php echo esc_attr($day); ?>" class="bible-nav-button bible-nav-next <?php echo esc_attr($bgClass); ?>" aria-label="Next day" style="<?php if (!empty($custom_background_color)) echo 'background-color: ' . esc_attr($custom_background_color) . ';'; ?>
        <?php if (!empty($text_color)) echo 'color: ' . esc_attr($text_color) . ';' ?>"><?php include plugin_dir_path(__FILE__) . '../assets/icons/right-arrow-icon.php'; ?></div>
            </div><span id="current-day" class="bible-current-day"><?php echo esc_html($formattedDate); ?></span>
            <div class="burger" id="open-days"><?php include plugin_dir_path(__FILE__) . '../assets/icons/menu-button.php'; ?></div>
        </div>

        <div class="days-panel" id="days-panel">
            <div class="days-panel-header">
                <div class="close-days" id="close-days">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
                        <path d="M18 6L6 18" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                        <path d="M6 6L18 18" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                    </svg>
                </div>
                <div class="days-panel-header-title"><?php echo esc_html(__('Our Reading Plan', 'bible-reading-plan')); ?></div>
            </div>

            <?php
            date_default_timezone_set($timezone);
            $schedule = bibldare_get_schedule_data();
            $currentDayOfYear = bibldare_get_today_index($timezone);
            ?>

            <div class="days-list">
                <?php for ($i = 1; $i <= 365; $i++): ?>
                    <?php
                    $dayReadings = $schedule[$i] ?? [];
                    $bookChapters = [];

                    foreach ($dayReadings as $reading) {
                        $bookName = bibldare_get_book_name_by_index($reading['bookIndex'], $language);
                        $chapters = array_map(fn($c) => $c['chapter'], $reading['chapters']);
                        $bookChapters[] = $bookName . ' ' . bibldare_format_chapters($chapters);
                    }

                    $isToday = ($i === $currentDayOfYear);
                    ?>

                    <div class="day-item <?php echo $isToday ? 'is-today' : ''; ?>" data-day="<?php echo esc_attr($i); ?>"
                        <?php if ($isToday)
                            echo 'id="today-scroll-target"'; ?>>
                        <p class="day-item-date">
                            <?php echo esc_html(bibldare_get_formatted_georgian_date($i, $language, $timezone)); ?>
                        </p>
                        <div class="day-item-schedule">
                            <?php foreach ($bookChapters as $line): ?>
                                <p><?php echo esc_html($line); ?></p>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endfor; ?>
            </div>
        </div>

        <div class="bible-schedule-loader">
            <div class="spinner"></div>
            <p><?php echo esc_html(__('loading', 'bible-reading-plan') . '...'); ?></p>
        </div>

        <div class="bible-schedule" data-day="<?php echo esc_attr($day); ?>" data-lang="<?php echo esc_attr($language); ?>"
            data-version="<?php echo esc_attr($version); ?>" data-background="<?php echo esc_attr($background); ?>"
            data-timezone="<?php echo esc_attr($timezone); ?>" data-custom-background-color="<?php echo esc_attr($custom_background_color); ?>"
            data-text-color="<?php echo esc_attr($text_color); ?>">
        </div>
    </div>
<?php
    $html = ob_get_clean();
    // Single newlines only so wpautop doesn't wrap blocks in <p> (it uses \n\n as paragraph break).
    $html = preg_replace('/\n\n+/', "\n", $html);
    // Remove empty p tags so they don't take space in flex layout.
    $html = preg_replace('/<p>\s*<\/p>/', '', $html);
    return $html;
});

function bibldare_get_day_books_chapters(
    $day,
    $language = DEFAULT_LANG,
    $version = DEFAULT_VERSION,
    $fetchBibleData = true
) {
    if ($fetchBibleData) {
        $dayData = bibldare_prepare_bible_schedule_data($day, $language, $version);
        if (!$dayData)
            return [];

        $result = [];

        foreach ($dayData as $book) {
            $chapters = array_map(
                fn($c) => $c['chapter'],
                $book['chapters']
            );

            $result[] = [
                'label' => $book['name'] . ' ' . bibldare_format_chapters($chapters)
            ];
        }

        return $result;
    }

    $schedule = bibldare_get_schedule_data();
    if (!isset($schedule[$day]))
        return [];

    $result = [];

    foreach ($schedule[$day] as $book) {
        $chapters = array_map(
            fn($c) => $c['chapter'],
            $book['chapters']
        );

        $bookName = bibldare_get_book_name_by_index(
            $book['bookIndex'],
            $language,
        );

        $result[] = [
            'label' => $bookName . ' ' . bibldare_format_chapters($chapters)
        ];
    }

    return $result;
}



function bibldare_prepare_bible_schedule_data($day, $language, $version)
{
    $cache_enabled = get_option('bibldare_bible_cache_enabled');

    $cache_key = 'bibldare_schedule_day_' . $day . '_' . $language . '_' . md5($version);

    $cached_data = get_transient($cache_key);

    if ($cached_data !== false && $cache_enabled) {
        return $cached_data;
    }

    // Get schedule data from database instead of file
    $bible_schedule_data = bibldare_get_schedule_data();

    if (!isset($bible_schedule_data[$day])) {
        return false;
    }

    $requestParams = [
        'mv' => $version,
        'language' => $language,
        'page' => 1,
    ];

    $nonEnglishBooksMap = [
        45 => 52,
        46 => 53,
        47 => 54,
        48 => 55,
        49 => 56,
        50 => 57,
        51 => 58,
        52 => 59,
        53 => 60,
        54 => 61,
        55 => 62,
        56 => 63,
        57 => 64,
        58 => 65,
        59 => 45,
        60 => 46,
        61 => 47,
        62 => 48,
        63 => 49,
        64 => 50,
        65 => 51,
    ];

    foreach ($bible_schedule_data[$day] as &$book) {
        foreach ($book['chapters'] as &$chapter) {
            $bookIndex = $book['bookIndex'];

            if ($language !== 'eng' && isset($nonEnglishBooksMap[$bookIndex])) {
                $bookIndex = $nonEnglishBooksMap[$bookIndex];
            }

            $bookIndex += 3;

            $queryParams = array_merge($requestParams, [
                'w' => $bookIndex,
                't' => $chapter['chapter'],
            ]);

            $url = BIBLDARE_BASE_URL . http_build_query($queryParams);
            $data = bibldare_fetch_bible_data($url);

            if (json_last_error() !== JSON_ERROR_NONE || !isset($data['bibleData'])) {
                $chapter['bibleData'] = [];
                continue;
            }

            $book['name'] = $data['bibleNames'][$bookIndex - 1];

            $from = $chapter['from'];
            $to = $chapter['to'];

            if (is_null($from) || is_null($to)) {
                $chapter['bibleData'] = $data['bibleData'];
            } else {
                $startIndex = max(0, $from - 1);
                $length = $to - $from + 1;
                $chapter['bibleData'] = array_slice($data['bibleData'], $startIndex, $length);
            }
        }
    }

    set_transient(
        $cache_key,
        $bible_schedule_data[$day],
        30 * DAY_IN_SECONDS
    );


    return $bible_schedule_data[$day];
}

// AJAX handler for loading Bible data
add_action('wp_ajax_bibldare_load_bible_schedule', 'bibldare_ajax_load_bible_schedule');
add_action('wp_ajax_nopriv_bibldare_load_bible_schedule', 'bibldare_ajax_load_bible_schedule');

function bibldare_ajax_load_bible_schedule()
{
    // if (!check_ajax_referer('bibldare_bible_schedule_nonce', 'nonce', false)) {
    //     wp_send_json_error(['message' => 'invalid_nonce']);
    //     return;
    // }

    $day = isset($_POST['day']) ? intval($_POST['day']) : 1;
    $lang = isset($_POST['lang']) ? $_POST['lang'] : DEFAULT_LANG;
    $version = isset($_POST['version']) ? $_POST['version'] : DEFAULT_VERSION;
    $background = sanitize_key($_POST['background'] ?? 'white');
    $timezone = isset($_POST['timezone']) ? $_POST['timezone'] : get_option('bibldare_bible_timezone', 'Asia/Tbilisi');
    $custom_background_color = isset($_POST['custom_background_color']) ? $_POST['custom_background_color'] : '';
    $text_color = isset($_POST['text_color']) ? $_POST['text_color'] : '';


    $formatedDate = bibldare_get_formatted_georgian_date($day, $lang, $timezone);

    $schedule_data = bibldare_prepare_bible_schedule_data($day, $lang, $version);

    if (!$schedule_data) {
        wp_send_json_error(['message' => __('No schedule found for this day.', 'bible-reading-plan')]);
        return;
    }

    ob_start();
?>
    <div class="bible-books-summary bible-bg-<?php echo esc_attr($background); ?>" style="<?php if (!empty($custom_background_color)) echo 'background-color: ' . esc_attr($custom_background_color) . ';'; ?> <?php if (!empty($text_color)) echo 'color: ' . esc_attr($text_color) . ';'; ?>">        
    <?php foreach ($schedule_data as $bookData): ?>

            <?php
            if (empty($bookData['chapters'])) {
                continue;
            }

            $chapters = $bookData['chapters'];
            $chapterFrom = $chapters[0]['chapter'];
            $chapterTo = $chapters[count($chapters) - 1]['chapter'];

            if ($chapterFrom === $chapterTo) {
                $chapterDisplay = $chapterFrom;
            } else {
                $chapterDisplay = $chapterFrom . '–' . $chapterTo;
            }
            ?>

            <p class="bible-book-summary-item">
                <strong><?php echo esc_html($bookData['name']); ?>:</strong>
                <?php echo esc_html($chapterDisplay); ?>
            </p>

        <?php endforeach; ?>

    </div><?php foreach ($schedule_data as $bookData): ?>
        <div class="bible-book bible-bg-<?php echo esc_attr($background); ?>" style="<?php if (!empty($custom_background_color)) echo 'background-color: ' . esc_attr($custom_background_color) . ';'; ?>
        <?php if (!empty($text_color)) echo 'color: ' . esc_attr($text_color) . ';' ?>">
        <h2 style="<?php if (!empty($text_color)) echo 'border-bottom: 2px solid ' . esc_attr($text_color) . ';' ?>"><?php echo esc_html($bookData['name']); ?></h2>

            <?php foreach ($bookData['chapters'] as $chapterData): ?>
                <?php
                $chapterNumber = $chapterData['chapter'];
                $from = $chapterData['from'];
                $to = $chapterData['to'];
                $hasRange = $from && $to;
                $verses = $chapterData['bibleData'] ?? [];
                ?>

                <div class="bible-chapter">
                    <h3>
                        <span class="chapter-label">
                            <?php echo esc_html(__('chapter', 'bible-reading-plan')); ?>
                        </span>
                        <?php echo esc_html($chapterNumber); ?>

                        <?php if ($hasRange): ?>
                            <span class="chapter-range">
                                (<?php echo esc_html(__('verses', 'bible-reading-plan')); ?>
                                <?php echo esc_html($from); ?>-<?php echo esc_html($to); ?>)
                            </span>
                        <?php endif; ?>
                    </h3>

                    <?php if (!empty($verses)): ?>
                        <div class="bible-verses">
                            <?php foreach ($verses as $verse): ?>
                                <div class="bible-verse">
                                    <span class="verse-number">
                                        <?php echo esc_html($verse['muxli']); ?>.
                                    </span>
                                    <span class="verse-text">
                                        <?php echo esc_html($verse['bv']); ?>
                                    </span>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <p class="error-message">
                            <?php echo esc_html__('No verses available for this chapter.'); ?>
                        </p>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endforeach; ?>

<?php

    $html = ob_get_clean();
    wp_send_json_success([
        'html' => $html,
        'formatedDate' => $formatedDate,
    ]);
}
