<?php
if ( ! defined( 'ABSPATH' ) ) exit;

function smpt_time_table_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'variant' => '',
        ),
        $atts,
        'timing_table_1'
    );
    ob_start();
    if ( get_option( 'smpt_salah_api_response' ) == 401 || get_option( 'smpt_salah_api_response' ) == 403 ) {
        return '';
    }

    $apiKey = sanitize_text_field( get_option( 'smpt_api_key' ) );

    $current_ts = current_datetime()->getTimestamp();
    $tomorrow_start = strtotime( 'tomorrow', $current_ts );

    if ( ! get_transient( 'smpt_calender_api_data' ) ) {
        $calender_date = smpt_get_calender_dates( current_time( "d-m-Y" ) );
        if ( $calender_date == false ) {
            return '';
        }
        set_transient( 'smpt_calender_api_data', $calender_date, $tomorrow_start - $current_ts );
    } else {
        $calender_date = get_transient( 'smpt_calender_api_data' );
    }

    if ( ! get_transient( 'smpt_prayer_api_data' ) ) {
        $response = get_smpt_api_data( $apiKey, current_time( "Y-m-d" ) );
        if ( $response == false ) {
            return '';
        }
        set_transient( 'smpt_prayer_api_data', $response, $tomorrow_start - $current_ts );
        $response = json_decode( $response );
        $salah_timings = $response->timings[0]->salah;
    } else {
        $response = get_transient( 'smpt_prayer_api_data' );
        $response = json_decode( $response );
        $salah_timings = $response->timings[0]->salah;
    }

    if ( ! get_transient( 'smpt_jumuah_api_data' ) ) {
        $response = get_smpt_jumuah_api_data( $apiKey, current_time( "Y-m-d" ) );
        if ( $response == false ) {
            return '';
        }
        set_transient( 'smpt_jumuah_api_data', $response, $tomorrow_start - $current_ts );
        $jumuah_timings = json_decode( $response, true );
    } else {
        $response = get_transient( 'smpt_jumuah_api_data' );
        $jumuah_timings = json_decode( $response, true );
    }

    $show_powered_by = get_option( 'smpt_show_powered_by', '1' );

    if ( get_option( 'smpt_table_style' ) <= 2 ) {
        smpt_render_table( $calender_date, $salah_timings, $jumuah_timings, $show_powered_by );
    } else {
        smpt_render_cards( $calender_date, $salah_timings, $jumuah_timings, $show_powered_by );
    }

    return ob_get_clean();
}

add_shortcode( 'smpt_time_table', 'smpt_time_table_shortcode' );
