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

include_once __DIR__ . '/includes/images/smpt_icons.php';

function add_smpt_shortcode_scripts() {
    if ( get_option( 'smpt_table_style', 1 ) == 1 )
        wp_enqueue_style( 'smpt_table_style', plugins_url( '/assets/css/smpt_table_style1.css', __FILE__ ) );
    else if ( get_option( 'smpt_table_style', 1 ) == 2 )
        wp_enqueue_style( 'smpt_table_style', plugins_url( '/assets/css/smpt_table_style2.css', __FILE__ ) );
    else if ( get_option( 'smpt_table_style', 1 ) == 3 ) {
        wp_enqueue_style( 'smpt_table_style', plugins_url( '/assets/css/smpt_table_style3.css', __FILE__ ) );
        $icon_color = sanitize_hex_color( get_option( 'smpt_icon_color_picker' ) );
        if ( $icon_color ) {
            wp_add_inline_style( 'smpt_table_style', '.smpt-table-icon path{fill:' . esc_attr( $icon_color ) . ';}' );
        }
        $active_icon_color = sanitize_hex_color( get_option( 'smpt_active_card_icon_color_picker' ) );
        if ( $active_icon_color ) {
            wp_add_inline_style( 'smpt_table_style', '.smpt-active-card .smpt-table-icon path{fill:' . esc_attr( $active_icon_color ) . ';}' );
        }
    }
}
add_action( 'wp_enqueue_scripts', 'add_smpt_shortcode_scripts' );

function add_smpt_admin_script() {
    wp_enqueue_script( 'smpt_admin_page_js', plugins_url( '/assets/js/smpt_admin_page.js', __FILE__ ) );
    wp_enqueue_style( 'smpt_admin_css', plugins_url( '/assets/css/smpt_admin.css', __FILE__ ) );
}
add_action( 'admin_enqueue_scripts', 'add_smpt_admin_script' );

function smpt_local_timestamp( $date, $time ) {
    return ( new DateTime( $date . ' ' . $time, wp_timezone() ) )->getTimestamp();
}

function smpt_render_powered_by() {
    echo '<p class="smpt-powered-by" style="text-align:center;font-size:0.8rem;opacity:0.7;margin-top:0.5rem;">'
        . sprintf( esc_html__( 'Powered by %s', 'smart-masjid-prayer-timings' ), '<a href="https://smartmasjid.app" target="_blank" rel="noopener noreferrer">Smart Masjid</a>' )
        . '</p>';
}

function smpt_render_table( array $calender_date, array $salah_timings, array $jumuah_timings, $show_powered_by = false ) {
    $src_set = SMPT_Icons::get_smpt_icon_set();
    $count = -1;
    $flag = true;
    ?>
    <div class="smpt-table-wrap">
        <h4><?php esc_html_e('Prayer Timings', 'smart-masjid-prayer-timings' ); ?></h4>
        <div id="smpt-date-header"><span><?php echo esc_html( $calender_date['gregorian']['day'] . ', ' . $calender_date['gregorian']['month']['en'] . ' ' . $calender_date['gregorian']['year'] ); ?></span>|<span><?php echo esc_html( $calender_date['hijri']['day'] . ', ' . $calender_date['hijri']['month']['en'] . ' ' . $calender_date['hijri']['year'] ); ?></span></div>
        <table class="smpt-table">
            <thead>
                <?php echo "<tr><th>" . esc_html__( 'Salah', 'smart-masjid-prayer-timings' ) . "</th><th>" . esc_html__( 'Adhan', 'smart-masjid-prayer-timings' ) . "</th><th>" . esc_html__( 'Iqama', 'smart-masjid-prayer-timings' ) . "</th></tr>"; ?>
            </thead>
            <tbody>
                <?php
                    $today = current_time( 'Y-m-d' );
                    $fajr_adhan_ts = smpt_local_timestamp( $today, $salah_timings[0]->adhanTime );
                    $isha_adhan_ts = smpt_local_timestamp( $today, $salah_timings[3]->adhanTime );
                    $isha_duration_bf_mid = ( strtotime( '+1 day', $fajr_adhan_ts ) - $isha_adhan_ts ) / 2;
                    $isha_duration_af_mid = ( $fajr_adhan_ts - strtotime( '-1 day', $isha_adhan_ts ) ) / 2;
                    $current_ts = current_datetime()->getTimestamp();
                    foreach ( $salah_timings as $index => $row ):
                        if ( $salah_timings[$index]->name == 'Fajr' && $current_ts > smpt_local_timestamp( $today, $salah_timings[$index]->adhanTime ) && $current_ts < smpt_local_timestamp( $today, $salah_timings[0]->sunriseTime ) && $flag ) {
                            $count = $index;
                            $flag = false;
                        }
                        elseif ( $salah_timings[$index]->name == 'Isha' && ( ( $current_ts > smpt_local_timestamp( $today, $salah_timings[$index]->adhanTime ) && $current_ts < $isha_duration_bf_mid + smpt_local_timestamp( $today, $salah_timings[$index]->adhanTime ) ) || ( $current_ts < $fajr_adhan_ts && $current_ts < $isha_duration_af_mid + strtotime( '-1 day', smpt_local_timestamp( $today, $salah_timings[$index]->adhanTime ) ) ) ) && $flag ) {
                            $count = $index;
                            $flag = false;
                        }
                        elseif ( $salah_timings[$index]->name != 'Fajr' && $salah_timings[$index]->name != 'Isha' && $current_ts > smpt_local_timestamp( $today, $salah_timings[$index]->adhanTime ) && $current_ts < smpt_local_timestamp( $today, $salah_timings[$index + 1]->adhanTime ) && $flag ) {
                            $count = $index;
                            $flag = false;
                        }
                ?>
                <tr <?php echo $count == $index ? 'class="smpt-active-row" title="current prayer"' : 'class="smpt-row"'; ?>>
                        <td><?php echo "<img src='" . esc_url( $src_set[$index] ) . "' class='smpt-table-icon'/>"; ?><?php echo esc_html( $salah_timings[$index]->name ); ?></td>
                        <td><?php echo esc_html( date( "g:i A", strtotime( $salah_timings[$index]->adhanTime ) ) ); ?></td>
                        <td><?php echo esc_html( date( "g:i A", strtotime( $salah_timings[$index]->iqamaTime ) ) ); ?></td>
                </tr>
                <?php
                    endforeach;
                ?>
            </tbody>
        </table>
        <div class='smpt-box-bottom'>
            <?php printf(
                "<div><img src='%s' class='smpt-table-icon' title='sunrise'/> Sunrise <br/>%s</div><div><img src='%s' class='smpt-table-icon' title='sunset'/> Shurooq <br/>%s</div>",
                esc_url( $src_set[5] ),
                esc_html( date( "g:i A", strtotime( $salah_timings[0]->sunriseTime ) ) ),
                esc_url( $src_set[6] ),
                esc_html( date( "g:i A", strtotime( $salah_timings[0]->shurooqTime ) ) )
            ); ?>
        </div>
        <table class="smpt-table">
            <thead>
                <tr>
                    <th><?php esc_html_e("Jumuah 1", 'smart-masjid-prayer-timings' ); ?></th>
                    <th><?php esc_html_e("Jumuah 2", 'smart-masjid-prayer-timings' ); ?></th>
                    <?php echo $jumuah_timings['jumuah3'] ? "<th> " . esc_html__( 'Jumuah 3', 'smart-masjid-prayer-timings' ) . "</th>" : ''; ?>
                </tr>
            </thead>
            <tbody>
                <tr class='smpt-row'>
                    <td><?php echo esc_html( date( "g:i A", strtotime( $jumuah_timings['jumuah1'] ) ) ); ?></td>
                    <td><?php echo $jumuah_timings['jumuah2'] ? esc_html( date( "g:i A", strtotime( $jumuah_timings['jumuah2'] ) ) ) : '-'; ?></td>
                    <?php echo $jumuah_timings['jumuah3'] ? "<td>" . esc_html( date( 'g:i A', strtotime( $jumuah_timings['jumuah3'] ) ) ) . "</td>" : ''; ?>
                </tr>
            </tbody>
        </table>
        <?php if ( $show_powered_by ) smpt_render_powered_by(); ?>
    </div>
    <?php
}

function smpt_render_cards( array $calender_date, array $salah_timings, array $jumuah_timings, $show_powered_by = false ) {
    $card_bg_color = sanitize_hex_color( get_option( 'smpt_card_color_picker' ) );
    $active_card_bg_color = sanitize_hex_color( get_option( 'smpt_active_card_color_picker' ) );
    $card_color = sanitize_hex_color( get_option( 'smpt_font_color_picker' ) );
    $active_card_color = sanitize_hex_color( get_option( 'smpt_active_card_font_color_picker' ) );
    $svg_icons = SMPT_Icons::get_smpt_svg();
    $count = -1;
    $flag = true;
    $current_ts = current_datetime()->getTimestamp();
    ?>
    <div id='smpt-card-section'>
        <div class="smpt-card-wrap">
            <?php $today = current_time( 'Y-m-d' ); ?>
            <?php foreach ( $salah_timings as $index => $row ): ?>
                <?php
                    if ( ( smpt_local_timestamp( $today, $salah_timings[$index]->iqamaTime ) > $current_ts ) && $flag ) {
                        $count = $index;
                        $flag = false;
                    }
                ?>
                <div style='background-color:<?php echo $count == $index ? ( $active_card_bg_color ? esc_attr( $active_card_bg_color ) : "#d8d8d8" ) : ( $card_bg_color ? esc_attr( $card_bg_color ) : '#fff' ); ?>;color:<?php echo $count == $index ? ( $active_card_color ? esc_attr( $active_card_color ) : ( $card_color ? esc_attr( $card_color ) : "#3e3e3e" ) ) : ( $card_color ? esc_attr( $card_color ) : "#3e3e3e" ); ?>;' class="smpt-card<?php echo $count == $index ? ' smpt-active-card' : ''; ?>">
                    <span><?php echo $svg_icons[$row->name]; ?></span>
                    <span class="card-header"><?php echo esc_html( $row->name ); ?></span>
                    <span><span><?php esc_html_e('Adhan', 'smart-masjid-prayer-timings' ); ?></span><?php echo esc_html( date( "g:i A", strtotime( $row->adhanTime ) ) ); ?></span>
                    <span><span><?php esc_html_e('Iqama', 'smart-masjid-prayer-timings' ); ?></span><?php echo esc_html( date( "g:i A", strtotime( $row->iqamaTime ) ) ); ?></span>
                </div>
            <?php endforeach; ?>
            <div style='background-color:<?php echo $card_bg_color ? esc_attr( $card_bg_color ) : '#fff' ?>;color:<?php echo $card_color ? esc_attr( $card_color ) : "#3e3e3e"; ?>;' class="smpt-card">
                <span><?php echo $svg_icons['sun-rise-shurooq']; ?></span>
                <span class="card-sub-header"><?php esc_html_e("Sunrise", 'smart-masjid-prayer-timings' ); ?></span>
                <span><?php echo esc_html( date( "g:i A", strtotime( $salah_timings[0]->sunriseTime ) ) ); ?></span>
                <span class="card-sub-header"><?php esc_html_e("Shurooq", 'smart-masjid-prayer-timings' ); ?></span>
                <span><?php echo esc_html( date( "g:i A", strtotime( $salah_timings[0]->shurooqTime ) ) ); ?></span>
            </div>
            <div style='background-color:<?php echo $card_bg_color ? esc_attr( $card_bg_color ) : '#fff' ?>;color:<?php echo $card_color ? esc_attr( $card_color ) : "#3e3e3e"; ?>;' class="smpt-card">
                <span><?php echo $svg_icons['Jumuah']; ?></span>
                <span class="card-sub-header"><?php esc_html_e("Jumuah", 'smart-masjid-prayer-timings' ); ?></span>
                <span class="jumuah-one"><?php echo esc_html( __( "First ", 'smart-masjid-prayer-timings' ) . date( "g:i A", strtotime( $jumuah_timings['jumuah1'] ) ) ); ?></span>
                <?php echo $jumuah_timings['jumuah2'] ? "<span class='jumuah-two'>" . esc_html( __( "Second ", 'smart-masjid-prayer-timings' ) . date( "g:i A", strtotime( $jumuah_timings['jumuah2'] ) ) ) . "</span>" : ''; ?>
                <?php echo $jumuah_timings['jumuah3'] ? "<span class='jumuah-three'>" . esc_html( __( "Third ", 'smart-masjid-prayer-timings' ) . date( "g:i A", strtotime( $jumuah_timings['jumuah3'] ) ) ) . "</span>" : ''; ?>
            </div>
        </div>
        <?php if ( $show_powered_by ) smpt_render_powered_by(); ?>
    </div>
    <?php
}

function smpt_get_calender_dates( string $date ) {
    $dt = DateTime::createFromFormat( 'd-m-Y', $date, wp_timezone() );
    if ( ! $dt ) return false;

    $gregorian = array(
        'day'   => $dt->format( 'j' ),
        'month' => array( 'en' => $dt->format( 'F' ) ),
        'year'  => $dt->format( 'Y' ),
    );

    if ( ! extension_loaded( 'intl' ) ) {
        return array(
            'gregorian' => $gregorian,
            'hijri'     => array(
                'day'   => '',
                'month' => array( 'en' => '' ),
                'year'  => '',
            ),
        );
    }

    $ts  = $dt->getTimestamp();
    $tz  = wp_timezone();
    $cal = IntlDateFormatter::TRADITIONAL;

    $hijri_day = new IntlDateFormatter( 'en@calendar=islamic-civil', IntlDateFormatter::FULL, IntlDateFormatter::NONE, $tz, $cal, 'd' );
    $hijri_month = new IntlDateFormatter( 'en@calendar=islamic-civil', IntlDateFormatter::FULL, IntlDateFormatter::NONE, $tz, $cal, 'MMMM' );
    $hijri_year = new IntlDateFormatter( 'en@calendar=islamic-civil', IntlDateFormatter::FULL, IntlDateFormatter::NONE, $tz, $cal, 'y' );

    return array(
        'gregorian' => $gregorian,
        'hijri'     => array(
            'day'   => $hijri_day->format( $ts ),
            'month' => array( 'en' => $hijri_month->format( $ts ) ),
            'year'  => $hijri_year->format( $ts ),
        ),
    );
}

function get_smpt_api_data( string $apiKey, string $date ) {
    $url = SMPT_API_BASE_URL . "/salah/timings?date=$date&apiKey=$apiKey";
    $response = wp_remote_get( $url );
    if ( is_wp_error( $response ) ) return false;
    $status = wp_remote_retrieve_response_code( $response );
    if ( $status != 200 ) return false;
    return wp_remote_retrieve_body( $response );
}

function get_smpt_jumuah_api_data( string $apiKey, string $date ) {
    $url = SMPT_API_BASE_URL . "/jumuah/timings?date=$date&apiKey=$apiKey";
    $response = wp_remote_get( $url );
    if ( is_wp_error( $response ) ) return false;
    $status = wp_remote_retrieve_response_code( $response );
    if ( $status != 200 ) return false;
    return wp_remote_retrieve_body( $response );
}

add_action( 'admin_notices', 'smpt_show_settings_saved_notice' );

function smpt_show_settings_saved_notice() {
    if ( isset( $_GET['settings-updated'] ) && sanitize_text_field( $_GET['settings-updated'] ) ) {
        ?>
        <div class="notice notice-success is-dismissible">
            <p><?php esc_html_e('Settings saved successfully!', 'smart-masjid-prayer-timings' ); ?></p>
        </div>
        <?php
    }
}
