<?php
/**
 * @package EGPS - Easy Sell for Google Photo
 */

if(!defined('ABSPATH')){
    exit; // Exit if accessed directly
}

///// start SESSION
function egps_start_session(){
    if(!session_id()) {
        //session_start();
    }
}
add_action('init', 'egps_start_session', 1);



///// WP-CRON setup
function egps_schedule_time( $schedules ) {
    $schedules['every_three_minutes'] = array(
        'interval'  => 12*60*60, //12 hours
        'display'   => __( 'Every 3 Minutes', 'egps-easy-sell-for-google-photo' )
    );
    return $schedules;
}
add_filter( 'cron_schedules', 'egps_schedule_time' );

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'egps_schedule_time' ) ) {
    wp_schedule_event( time(), 'every_three_minutes', 'egps_schedule_time' );
}

function egps_schedule_do() {

    //get album data from Google Photos and save to database
    EgpsAlbums::egps_process_google_albums('');

    //download album covers from Google Photos
    EgpsAlbums::egps_download_images("photos", true);

    //download data for images in each albums
    EgpsAlbums::egps_sync_albums();
    
    //download/sync photos
    EgpsAlbums::egps_download_images("photos", true);

}
add_action( 'egps_schedule_time', 'egps_schedule_do' );

// function for deactivation hook
function egps_schedule_deactivation() {
    // clear scheduled hook
    wp_clear_scheduled_hook( 'egps_schedule_time' );
}
register_deactivation_hook(__FILE__, 'egps_schedule_deactivation');
////// /CRON


// Create Google authenticate definied variables
EgpsAuthenticate::egps_auth_variables();

// Create PayPal variables
EgpsPayPal::egps_paypal_variables();


///// check Google API token validity
EgpsAuthenticate::check_token();

///// get Google API token on admin button click
if(isset($_GET['code'])) {

    $egps_token = EgpsAuthenticate::egps_get_token( sanitize_text_field($_GET['code']) );
    $egps_token_array = json_decode($egps_token['body'], true);
    
    if (!array_key_exists('error', $egps_token_array)) {
        define('EGPS_TOKEN', $egps_token_array['access_token']);
        define('EGPS_TOKEN_REFRESH', $egps_token_array['refresh_token']);
        define('EGPS_TOKEN_EXPIRES', EgpsAuthenticate::count_token_expire_time($egps_token_array['expires_in']));
    }else {
        define('EGPS_TOKEN', EGPS_G_ACCESS_TOKEN);
        define('EGPS_TOKEN_REFRESH', EGPS_G_REFRESH_TOKEN);
        define('EGPS_TOKEN_EXPIRES', EGPS_G_TOKEN_EXPIRETIME);
    }

}else {
    define('EGPS_TOKEN', EGPS_G_ACCESS_TOKEN);
    define('EGPS_TOKEN_REFRESH', EGPS_G_REFRESH_TOKEN);
    define('EGPS_TOKEN_EXPIRES', EGPS_G_TOKEN_EXPIRETIME);
}


///// check PayPal token
EgpsPayPal::egps_check_pp_token();

///// get PayPal token on admin button click
if(isset($_GET["getpptoken"])){
    $pptoken_ret = EgpsPayPal::egps_get_paypal_token();

    if($pptoken_ret != null){
        EgpsPayPal::egps_save_pp_token($pptoken_ret);
    }
}


///// add custom CSS, JS, BOOTSTRAP
function egps_load_style(){
    wp_register_style('egps_admin_css', plugin_dir_url(__FILE__) . 'css/egps_admin.css', array(), EGPS_VERSION);
    wp_enqueue_style ('egps_admin_css');

    wp_register_style('egps_bootstrap_css', EGPS_BASE_PLUGIN . 'libs/bootstrap/bootstrap.css', array(), EGPS_VERSION);
    wp_enqueue_style('egps_bootstrap_css');

    wp_register_script('egps_bootstrap_js', EGPS_BASE_PLUGIN . 'libs/bootstrap/bootstrap.js', array(), EGPS_VERSION, false);
    wp_enqueue_script('egps_bootstrap_js');

    //wp_register_script('egps_jquery_js', EGPS_BASE_PLUGIN . 'public/js/jquery3.7.1.js', array(), EGPS_VERSION, false);
    //wp_enqueue_script('egps_jquery_js');

    wp_register_script('egps_functions_js', plugin_dir_url(__FILE__) . 'js/functions.js', array(), EGPS_VERSION, false);
    wp_enqueue_script('egps_functions_js');

    wp_register_style('egps_frontend_css', EGPS_BASE_PLUGIN . 'frontend/build/static/css/egps_allinonefile.css', array(), EGPS_VERSION);
    wp_enqueue_style ('egps_frontend_css');

    wp_register_script('egps_frontend_react_js', EGPS_BASE_PLUGIN . 'frontend/build/static/js/egps_allinonefile.js', array(), EGPS_VERSION, false);
    wp_enqueue_script ('egps_frontend_react_js');

}
add_action( 'admin_enqueue_scripts', 'egps_load_style' );


function egps_load_frontend_style(){
    wp_register_style('egps_bootstrap_css', EGPS_BASE_PLUGIN . 'libs/bootstrap/bootstrap.min.css', array(), EGPS_VERSION);
    wp_enqueue_style('egps_bootstrap_css');

    wp_register_script('egps_bootstrap_js', EGPS_BASE_PLUGIN . 'libs/bootstrap/bootstrap.min.js', array(), EGPS_VERSION, false);
    wp_enqueue_script('egps_bootstrap_js');

    //wp_register_script('egps_jquery_js', EGPS_BASE_PLUGIN . 'public/js/jquery3.7.1.js', array(), EGPS_VERSION, false);
    //wp_enqueue_script('egps_jquery_js');
    
    wp_register_script('egps_functions_frontend_js', EGPS_BASE_PLUGIN . 'libs/js/egps_frontend.js', array(), EGPS_VERSION, false);
    wp_enqueue_script('egps_functions_frontend_js');

    wp_register_style('egps_frontend_css', EGPS_BASE_PLUGIN . 'libs/css/egps_frontend.css', array(), EGPS_VERSION);
    wp_enqueue_style ('egps_frontend_css');

    wp_register_style('egps_frontend_react_css', EGPS_BASE_PLUGIN . 'frontend/build/static/css/egps_allinonefile.css', array(), EGPS_VERSION);
    wp_enqueue_style ('egps_frontend_react_css');

    wp_register_script('egps_frontend_js', EGPS_BASE_PLUGIN . 'frontend/build/static/js/egps_allinonefile.js', array(), EGPS_VERSION, false);
    wp_enqueue_script ('egps_frontend_js');

}
//called in views

function egps_load_js_script(){
    wp_register_script('egps_functions_js', plugin_dir_url(__FILE__) . 'js/functions.js', array('jquery'), EGPS_VERSION, false);
    wp_enqueue_script('egps_functions_js');
}
//called in views


///// create menu structure
function egps_admin_menu_html_settings() {

    $default_tab = 'google_api';

    $tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : $default_tab;

    ?>
    <div class="wrap">
        <h2 class="nav-tab-wrapper">
        <a class="nav-tab <?php echo ($tab == 'google_api') ? 'nav-tab-active' : ''; ?>"
               id="egps_settings_options_google"
               href="admin.php?page=easy-photo-sell_settings&tab=google_api">
                <span class="icon">&nbsp;</span>Google Photos API</a>

                <a class="nav-tab <?php echo ($tab == 'firebase_api') ? 'nav-tab-active' : ''; ?>"
               id="egps_settings_options_firebase"
               href="admin.php?page=easy-photo-sell_settings&tab=firebase_api">
                <span class="icon">&nbsp;</span>Firabase API</a>

            <a class="nav-tab <?php echo ($tab == 'site_design') ? 'nav-tab-active' : ''; ?>"
               id="egps_settings_options_site_design"
               href="admin.php?page=easy-photo-sell_settings&tab=site_design">
                <span class="icon">&nbsp;</span>Design</a>

            <a class="nav-tab <?php echo ($tab == 'photometa') ? 'nav-tab-active' : ''; ?>"
               id="egps_settings_options_photometa"
               href="admin.php?page=easy-photo-sell_settings&tab=photometa">
                <span class="icon">&nbsp;</span>Photo's metadata</a>

            <a class="nav-tab <?php echo ($tab == 'license') ? 'nav-tab-active' : ''; ?>"
               id="egps_settings_options_license"
               href="admin.php?page=easy-photo-sell_settings&tab=license">
                <span class="icon">&nbsp;</span>License Key</a>

            <?php 
                if( Egps::egps_chk_lic() ) {
                    echo '
                    <a class="nav-tab ' . (($tab == 'prices') ? 'nav-tab-active' : '') . '" 
                        id="egps_settings_options_prices"
                        href="admin.php?page=easy-photo-sell_settings&tab=prices">
                        <span class="icon">&nbsp;</span>Photo prices</a>

                    <a class="nav-tab ' . (($tab == 'paypal') ? 'nav-tab-active' : '') . '" 
                        id="egps_settings_options_paypal"
                        href="admin.php?page=easy-photo-sell_settings&tab=paypal">
                        <span class="icon">&nbsp;</span>PayPal</a>
                    ';

                }
            ?>

        </h2>
    </div>
    <div class="tab-content" style="margin-top: 1.2rem">

        <?php

            switch($tab){
                case 'google_api':
                    require_once 'views/settings.php';
                    break;

                case 'firebase_api':
                    require_once 'views/settings_firebase.php';
                    break;

                case 'site_design':
                    require_once 'views/site_design.php';
                    break;

                case 'photometa':
                    require_once 'views/photometa.php';
                    break;

                case 'prices':
                    require_once 'views/prices.php';
                    break;

                case 'paypal':
                    require_once 'views/paypal.php';
                    break;
                        
                case 'license':
                    require_once 'views/license.php';
                    break;
            
                default:
                    require_once 'views/settings.php';
                    break;
            }

        ?>

    </div>

    <?php

}

function egps_admin_menu_html_readme(){
    try{
        $admin_menu_out = file_get_contents(dirname(__DIR__) . '/readme.txt'); 
        echo '<pre style="max-width: 100%; white-space: pre-wrap;">' . esc_html($admin_menu_out) . '</pre>';
    }catch (Error $e){
        echo esc_html($e);
    }
}

function egps_admin_menu_html_albums(){

    $myurl = admin_url( "admin.php?page=easy-photo-sell_albums");
    $nonceurl = wp_nonce_url($myurl, "albums", "_egpsnonce");

    if( isset($_GET['_egpsnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_egpsnonce'])), 'albums')){
        $email = isset( $_POST['cust_email']) ? sanitize_text_field($_POST['cust_email']) : "";
    }


    echo '<p>
    To refresh albums, photos in your store manually, click on the buttons in the given order. 
    <strong>WAIT for the process to finish!</strong> <br>
    Completing the update may take several minutes, depending on your album and photo count.

    <br><b>IMPORTANT:</b> 
    <br><strong><b style="color: red">DO NOT DELETE PHOTOS OR ALBUMS</b>  on Google Photos.
    Instead, set visibility here in the EGPS admin panel </strong><br>

    Once you upload and arrange your photos into albums, please do not make any changes to their arrangement. 
    <br>This is important because the Google Photos API does not support photo deletion, 
    and <b>photos that have been purchased must remain available for download in their original location.</b> 
    Thank you for your understanding.

    </p>';

    if( !isset($_GET['show_album_photos']) ){
        echo '<div class="egps_admin_albums_btn_div">';
        echo '<a id="egps_admin_update_album_database" class="button button-primary" href="#">1. Sync albums</a>&nbsp;';
        echo '<a id="egps_admin_update_photo_database" class="button button-primary" href="#">2. Sync photos (meta)</a>&nbsp;';
        echo '<a id="egps_admin_dwnld_images" class="button button-primary" href="#">3. Import photos</a>';
        echo '</div>';
        echo '<div class="progress" style="margin-top: 50px;width:50%;">
                        <div class="progress-bar active" id="progressbar" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 0%; background-color: #399;">
                            <span class="sr-only">0% Complete</span>
                        </div>
                    </div>';
    
    }
    echo '<div class="loading_gif"><!-- Loading icon --></div>';

    //set progress bar to zero
    Egps::egps_zero_progress();


    // button 1. (Sync albums) in admin panel
    // egps_admin_update_album_database click on button
    if(isset($_GET['list_albums']) && $_GET['list_albums'] == '1'){
        //sign all albums to delete (existing albums will be set to delete = 0 in egps_process_google_albums funciton)
        /*
            DISABLED
            Do NOT delete photos or albums from Google Photos, set visibility in EGPS admi panel!
            IMPORTANT! If the photo was purchased already, the buyer wont be able to download it!
        */
        //EgpsDatabase::egps_update_db_table_allrows("egps_item_for_delete", 1);

        //get album data from Google Photos and save to database
        EgpsAlbums::egps_process_google_albums('');

        //download album covers from Google Photos
        //progress bar showing when downloading images
        EgpsAlbums::egps_download_images("albums", true);

        exit;

    }

    // button 2. (Sync photos - meta) in admi nanel
    // egps_admin_update_photo_database click on button
    if(isset($_GET['sync_photo_data']) && $_GET['sync_photo_data'] == '1'){
        //download data for images in each albums
        EgpsAlbums::egps_sync_albums();

        exit;
    }

    // button 3. (Immport photos) in admin panel
    if(isset($_GET['download_images']) && $_GET['download_images'] == '1'){
        EgpsAlbums::egps_download_images("photos", true);
    }


    if(isset($_GET['change_show_hide']) && $_GET['change_show_hide'] == 1){
        EgpsAlbums::egps_change_album_show(
            sanitize_text_field($_GET['bt_id']), 
            sanitize_text_field($_GET['bt_val'])
        );
    }

    if(isset($_GET['change_show_hide_photo']) && $_GET['change_show_hide_photo'] == 1){
        EgpsAlbums::egps_change_photo_show(
            sanitize_text_field($_GET['bt_id']), 
            sanitize_text_field($_GET['bt_val'])
        );
    }


    if(isset($_GET['zero_progress']) && $_GET['zero_progress'] == 1){
        Egps::egps_zero_progress();
    }

    // list photos from one album
    if(isset($_GET['show_album_photos'])){
        // list photos from album
        require_once 'views/album_photos.php';
    }else{
        // listing all albums from database
        // $album_data_array passed to albums.php to show albums list
        $album_data_array = EgpsDatabase::egps_get_table_rows('egps_albums', 'egps_title', 'ASC');
        require_once 'views/albums.php';
    }

}

function egps_admin_menu_html_purchased(){
    $default_tab = 'customers';

    $tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : $default_tab;

    ?>
    <div class="wrap">
        <h2 class="nav-tab-wrapper">

            <a class="nav-tab <?php echo ($tab == 'customers') ? 'nav-tab-active' : ''; ?>"
               id="egps_order_options_customers"
               href="admin.php?page=easy-photo-sell_orders&tab=customers">
                <span class="icon">&nbsp;</span>Customers
            </a>

            <a class="nav-tab <?php echo ($tab == 'last_ordered') ? 'nav-tab-active' : ''; ?>"
               id="egps_order_options_last_ordered"
               href="admin.php?page=easy-photo-sell_orders&tab=last_ordered">
                <span class="icon">&nbsp;</span>Last ordered
            </a>

            <a class="nav-tab <?php echo ($tab == 'most_ordered') ? 'nav-tab-active' : ''; ?>"
               id="egps_order_options_most_ordered"
               href="admin.php?page=easy-photo-sell_orders&tab=most_ordered">
                <span class="icon">&nbsp;</span>Most ordered
            </a>

        </h2>
    </div>
    <div class="tab-content">

        <?php

            switch($tab){
                case 'customers':
                    require_once 'views/order_customers.php';
                    break;

                    case 'last_ordered':
                        require_once 'views/order_last.php';
                        break;
    
                    case 'most_ordered':
                        require_once 'views/order_most.php';
                        break;
    
                            default:
                    require_once 'views/order_customers.php';
                    break;
            }

        ?>

    </div>

    <?php
}

function egps_admin_email_menu(){

    $default_tab = 'settings';

    $tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : $default_tab;

    ?>
    <div class="wrap">
        <h2 class="nav-tab-wrapper">

            <a class="nav-tab <?php echo ($tab == 'settings') ? 'nav-tab-active' : ''; ?>"
               id="egps_settings_email_settings"
               href="admin.php?page=email_settings&tab=settings">
                <span class="icon">&nbsp;</span>Settings</a>

            <a class="nav-tab <?php echo ($tab == 'registration') ? 'nav-tab-active' : ''; ?>"
               id="egps_settings_email_reg"
               href="admin.php?page=email_settings&tab=registration">
                <span class="icon">&nbsp;</span>Registration</a>

            <a class="nav-tab <?php echo ($tab == 'order') ? 'nav-tab-active' : ''; ?>"
               id="egps_settings_email_order"
               href="admin.php?page=email_settings&tab=order">
                <span class="icon">&nbsp;</span>Orders</a>

        </h2>
    </div>
    <div class="tab-content" style="margin-top: 1.2rem">

        <?php

            switch($tab){
                case 'settings':
                    require_once 'views/email_settings.php';
                    break;

                case 'registration':
                    require_once 'views/email_registration.php';
                    break;
    
                case 'order':
                    require_once 'views/email_order.php';
                    break;
            
                default:
                    require_once 'views/email_settings.php';
                    break;
            }

        ?>

    </div>

    <?php
}

function egps_helpmenu(){
    require_once dirname(dirname(__FILE__)) . '/common/views/egps_helpmenu.php';
    require_once dirname(dirname(__FILE__)) . '/common/views/egps_helpmenu_videos.php';
}

function egps_admin_menu_html_test(){
    //TODO
    //FOR testing purposes

}


function egps_create_options_page() {
    add_menu_page(
        'EGPS - Easy Sell for Google Photo', //page title
        'EGPS', //menu title
        'manage_options', //capability
        'easy-photo-sell', //menu slug
        'egps_admin_menu_html_readme', //callback function
        plugin_dir_url(__FILE__) . 'images/sell_google_photos_icon_36.png', //icon
        100 //int position
    );

    add_submenu_page(
        'easy-photo-sell', //parent slug
        'EGPS - Easy Sell for Google Photo - Settings', //page title
        'EGPS - Settings', //menu title
        'manage_options', //capability
        'easy-photo-sell_settings', //slug
        'egps_admin_menu_html_settings', //callback function for html
        1 //position int
    );

    add_submenu_page(
        'easy-photo-sell', //parent slug
        'EGPS - Easy Sell for Google Photo - Albums', //page title
        'EGPS - Albums', //menu title
        'manage_options', //capability
        'easy-photo-sell_albums', //slug
        'egps_admin_menu_html_albums', //callback function for html
        3 //position int
    );

    add_submenu_page(
        'easy-photo-sell', //parent slug
        'EGPS - Easy Sell for Google Photo - Orders', //page title
        'EGPS - Orders', //menu title
        'manage_options', //capability
        'easy-photo-sell_orders', //slug
        'egps_admin_menu_html_purchased', //callback function for html
        4 //position int
    );

    add_submenu_page(
        'easy-photo-sell', //parent slug
        'EGPS - Easy Sell for Google Photo - Emails', //page title
        'EGPS - Emails', //menu title
        'manage_options', //capability
        'email_settings', //slug
        'egps_admin_email_menu', //callback function for html
        2 //position int
    );

    add_submenu_page(
        'easy-photo-sell', //parent slug
        'EGPS - HELP', //page title
        'EGPS - HELP', //menu title
        'manage_options', //capability
        'egps_helpmenu', //menu slug
        'egps_helpmenu', //callback function
        //plugin_dir_url(__FILE__) . 'images/egps_faq.png', //icon
        5 //int position
    );

    // TODO test
    /*
    add_submenu_page(
        'easy-photo-sell', //parent slug
        'EGPS - Test', //page title
        'EGPS - Testpage', //menu title
        'manage_options', //capability
        'easy-photo-sell_test', //slug
        'egps_admin_menu_html_test', //callback function for html
        6 //position int
    );
    */

    }
add_action( 'admin_menu', 'egps_create_options_page' );


///// REGISTER
register_setting('egps_client_data', 'egps_options');
register_setting('egps_paypal_data', 'egps_paypal_options');
register_setting('egps_firebase_data', 'egps_firebase_options');
register_setting('egps_photo_data', 'egps_photometa');
register_setting('egps_prices_data', 'egps_prices');
register_setting('egps_site_design', 'egps_sitedesign');
register_setting('egps_license_data', 'egps_license_options');
register_setting('egps_email_data', 'egps_email_options');
register_setting('egps_email_order_data', 'egps_email_order_options');
register_setting('egps_email_settings_data', 'egps_email_settings_options');



///// Create plugin frontend pages as templates
function egps_create_custom_template( $post_templates, $wp_theme, $post, $post_type ) {

    // Add custom template to select dropdown
    $post_templates['frontend_gallery.php'] = 'EGPS Gallery';

    return $post_templates;
}
add_filter( 'theme_page_templates', 'egps_create_custom_template', 10, 4);


// load data in template files for each specific url
function egps_add_custom_template( $template ) {
    if(  get_page_template_slug() === 'frontend_gallery.php' ) {

        $template = dirname(dirname(__FILE__)) . '/common/views/frontend_gallery.php';
        
    }

    return $template;
}
add_filter( 'template_include', 'egps_add_custom_template' );


// custom rewrite rules for ReactJs to work
$template_ids = EgpsDatabase::egps_get_table_rows_where_in_posts();

if( !empty($template_ids)){

    $id_camera = $template_ids[0]->ID;
    $id_tag = $template_ids[1]->ID;
    $id_photoalbum = $template_ids[2]->ID;

    
    function egps_custom_rewrite_rules() {
        add_rewrite_rule(
            '^photoalbum/([0-9a-z-]+)/?$',
            'index.php?pagename=photoalbum&album_id=$matches[1]',
            'top'
        );
        add_rewrite_rule(
            '^photoalbum/([0-9a-z-]+)/([0-9a-z-]+)/?$',
            'index.php?pagename=photoalbum&album_id=$matches[1]&photo_id=$matches[2]',
            'top'
        );
        add_rewrite_rule(
            '^egpstag/([0-9a-z-]+)/?$',
            'index.php?pagename=egpstag&tag_id=$matches[1]',
            'top'
        );
        add_rewrite_rule(
            '^egpstag/([0-9a-z-]+)/([0-9a-z-]+)/?$',
            'index.php?pagename=egpstag&tag_id=$matches[1]&photo_id=$matches[2]',
            'top'
        );
        add_rewrite_rule(
            '^egpscamera/([0-9a-z-]+)/?$',
            'index.php?pagename=egpscamera&tag_id=$matches[1]',
            'top'
        );
        add_rewrite_rule(
            '^egpscamera/([0-9a-z-]+)/([0-9a-z-]+)/?$',
            'index.php?pagename=egpscamera&tag_id=$matches[1]&photo_id=$matches[2]',
            'top'
        );
    }
    add_action('init', 'egps_custom_rewrite_rules');    


    function egps_custom_query_vars_camera($query_vars) {
        $query_vars[] = 'album_id';
        $query_vars[] = 'tag_id';
        $query_vars[] = 'photo_id';
        return $query_vars;
    }
    add_filter('query_vars', 'egps_custom_query_vars_camera');
    
}


//CORS
function egps_cours_out() {
    //header("Access-Control-Allow-Origin: *" );
    //header("Access-Control-Allow-Methods: GET" );
}
//add_action('init','egps_cours_out');
