<?php

/**
 * @package: EGPS - Easy Sell for Google Photo
 */

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

class EgpsREST extends WP_REST_Controller{

    function __construct(){
        add_action( 'rest_api_init', [$this, 'define_egps_endpoint'] );
    }


    function define_egps_endpoint() {
        
        register_rest_route( 
            'egps_rest', 'get_add_to_cart_buttons', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_add_to_cart_buttons'],
            )
        );

        register_rest_route( 
            'egps_rest', 'get_albums', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_albums'],
            )
        );

        register_rest_route( 
            'egps_rest', 'get_albums_order/(?P<order>([a-z])+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_albums_order'],
                'args' => array(
                    'order' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_string( $param );
                        }
                    ),
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'get_tagcloud', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_tagcloud'],
            )
        );

        register_rest_route( 
            'egps_rest', 'get_photo_list/(?P<id>([a-zA-Z0-9.-])+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_photolist'],
                'args' => array(
                    'id' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_string( $param );
                        }
                    ),
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'get_photo_list_order/(?P<id>([a-zA-Z0-9.-])+)/(?P<order>([a-z])+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_photolist_order'],
                'args' => array(
                    'id' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_string( $param );
                        }
                    ),
                    'order' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    )
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'get_tagsearch/(?P<tagname>([a-zA-Z0-9.-])+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_tagsearch'],
                'args' => array(
                    'tagname' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_string( $param );
                        }
                    ),
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'get_tagsearch_order/(?P<tagname>([a-zA-Z0-9.-])+)/(?P<order>([a-z])+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_tagsearch_order'],
                'args' => array(
                    'tagname' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_string( $param );
                        }
                    ),
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'get_camerasearch/(?P<tagname>([a-zA-Z0-9.-])+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_camerasearch'],
                'args' => array(
                    'tagname' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            //return is_string( $param );
                            return true;
                        }
                    ),
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'get_camerasearch_order/(?P<tagname>([a-zA-Z0-9.-])+)/(?P<order>([a-z])+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_camerasearch_order'],
                'args' => array(
                    'tagname' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            //return is_string( $param );
                            return true;
                        }
                    ),
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'get_photo_data/(?P<id>\d+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_photo_data'],
                'args' => array(
                    'id' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_numeric( $param );
                        }
                    ),
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'get_photo_permission/(?P<id>\d+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_photo_permission'],
                'args' => array(
                    'id' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_numeric( $param );
                        }
                    ),
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'get_prices_data', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_currency_and_price']
            )
        );

        register_rest_route( 
            'egps_rest', 'get_photo_per_page_data', array(
                'methods' => 'GET',
                'callback' => [$this, 'get_egps_photo_per_page']
            )
        );

        register_rest_route( 
            'egps_rest', 'get_firebase_data', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_get_firebase_data']
            )
        );

        register_rest_route(
            'egps_rest', 'get_sum_price/(?P<email>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_sum_price'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                )
            )
        );

        register_rest_route(
            'egps_rest', 'egps_send_email_reg/(?P<email>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_send_email_reg'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                )
            )
        );

        register_rest_route(
            'egps_rest', 'get_client_photos/(?P<email>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_client_photos'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                )
            )
        );

        register_rest_route(
            'egps_rest', 'get_client_invoices/(?P<email>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_return_get_client_invoices'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                )
            )
        );

        register_rest_route(
            'egps_rest', 'get_photo_production/(?P<email>\S+)/(?P<id>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_get_photo_production'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                    'id' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    )
                )
            )
        );

        register_rest_route(
            'egps_rest', 'inc_dwldcount/(?P<email>\S+)/(?P<id>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_inc_dwldcount'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                    'id' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    )
                )
            )
        );

        register_rest_route(
            'egps_rest', 'get_order_details/(?P<email>\S+)/(?P<id>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_get_order_details'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                    'id' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    )
                )
            )
        );

        register_rest_route(
            'egps_rest', 'egps_save_order/(?P<email>\S+)/(?P<id>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_save_order_to_db'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                    'id' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    )
                )
            )
        );

        register_rest_route(
            'egps_rest', 'egps_empty_cart_db/(?P<email>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_empty_cart_db'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                )
            )
        );

        register_rest_route(
            'egps_rest', 'egps_save_cart_to_db/(?P<email>\S+)/(?P<text>\S+)/(?P<items>\S+)', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_save_cart_to_db'],
                'args' => array(
                    'email' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                    'text' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                    'items' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    ),
                )
            )
        );

        register_rest_route(
            'egps_rest', 'egps_get_pp_clientid', array(
                'methods' => 'GET',
                'callback' => [$this, 'egps_get_pp_clientid'],
                'args' => array(
                    'data' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return  is_string($param) ;
                        }
                    )
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'update_egps_lickey', array(
                'methods' => 'POST',
                'callback' => [$this, 'egps_update_egps_lickey'],
                'args' => array(
                    'ak' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_string( $param );
                        }
                    )
                )
            )
        );

        register_rest_route( 
            'egps_rest', 'update_egps_photometa', array(
                'methods' => 'POST',
                'callback' => [$this, 'egps_update_photometadata'],
                'args' => array(
                    'egps_desc' => array( 
                        'validate_callback' => function( $param, $request, $key ) {
                            return is_string( $param );
                        }
                    )
                )
            )
        );



    }
    
    function egps_return_get_add_to_cart_buttons() {

        $egps_lic = get_option('egps_license_options');

        $dcrypted = new EgpsAuthenticate;

        $dec_key = $dcrypted->egps_decrypt_key(
            $egps_lic['egps_license_key'], 
            $egps_lic['egps_api_key']
        );

        return rest_ensure_response( $dec_key[1] );

    }

    function egps_return_get_albums() {

        $album_data_array = EgpsAlbums::egps_get_active_albums('egps_title', 'ASC', "rest");

        return rest_ensure_response( $album_data_array );
    }

    function egps_return_get_albums_order($data) {

        $album_data_array = EgpsAlbums::egps_get_active_albums($data['order'], 'DESC', 'rest_order');

        return rest_ensure_response( $album_data_array );
    }

    function egps_return_get_tagcloud() {
        $fields = array( "egps_tag" );

        $tag_array = EgpsDatabase::egps_get_table_rows(
            'egps_tagcloud', 
            'egps_tag',
            'ASC'
        );

        $tagout = [];
        $i = 0;

        foreach($tag_array as $tag){
            $str = str_replace("#", "", $tag->egps_tag);

            $tagout[$i]["label"] = $str;
            $tagout[$i]["value"] = $str;

            $i++;
        }

        return rest_ensure_response( $tagout );
    }

    function egps_return_get_photolist($data) {

        if(isset($data['id'])){
            $album_data_array = EgpsAlbums::egps_get_album_photos($data['id']);

            $new_array = array();

            foreach($album_data_array as $key => $val){

                $new_array[$key] = $val;

                $new_array[$key]->metadata = json_decode( $album_data_array[$key]->egps_mediaMetadata, true);
            }
            
            return rest_ensure_response( $new_array );
        }
        return null;

        
    }

    function egps_return_get_photolist_order($data) {

        if(isset($data['id'])){
            $album_data_array = EgpsAlbums::egps_get_album_photos_order($data['id'], $data['order']);

            $new_array = array();

            foreach($album_data_array as $key => $val){

                $new_array[$key] = $val;

                $new_array[$key]->metadata = json_decode( $album_data_array[$key]->egps_mediaMetadata, true);
            }
            
            return rest_ensure_response( $new_array );
        }
        return null;

        
    }

    function egps_return_get_tagsearch($data) {

        if(isset($data)){
            $album_data_array = EgpsAlbums::egps_get_tagsearch_photos($data['tagname']);

            if( empty($album_data_array)){
                return rest_ensure_response(null);
            }

            $new_array = array();

            foreach($album_data_array as $key => $val){

                $new_array[$key] = $val;

                $new_array[$key]->metadata = json_decode( $album_data_array[$key]->egps_mediaMetadata, true);
            }
            
            return rest_ensure_response( $new_array );
        }
        return null;

        
    }

    function egps_return_get_tagsearch_order($data) {

        if(isset($data)){
            $album_data_array = EgpsAlbums::egps_get_tagsearch_photos($data['tagname'], $data['order'] );

            if( empty($album_data_array)){
                return rest_ensure_response(null);
            }

            $new_array = array();

            foreach($album_data_array as $key => $val){

                $new_array[$key] = $val;

                $new_array[$key]->metadata = json_decode( $album_data_array[$key]->egps_mediaMetadata, true);
            }
            
            return rest_ensure_response( $new_array );
        }
        return null;

        
    }

    function egps_return_get_camerasearch($data) {

        if(isset($data)){
            $album_data_array = EgpsAlbums::egps_get_camerasearch_photos($data['tagname']);

            if( empty($album_data_array)){
                return rest_ensure_response(null);
            }

            $new_array = array();

            foreach($album_data_array as $key => $val){

                $new_array[$key] = $val;

                $new_array[$key]->metadata = json_decode( $album_data_array[$key]->egps_mediaMetadata, true);
            }
            
            return rest_ensure_response( $new_array );
        }
        return null;

    }

    function egps_return_get_camerasearch_order($data) {

        if(isset($data)){
            $album_data_array = EgpsAlbums::egps_get_camerasearch_photos($data['tagname'], $data['order']);

            if( empty($album_data_array)){
                return rest_ensure_response(null);
            }

            $new_array = array();

            foreach($album_data_array as $key => $val){

                $new_array[$key] = $val;

                $new_array[$key]->metadata = json_decode( $album_data_array[$key]->egps_mediaMetadata, true);
            }
            
            return rest_ensure_response( $new_array );
        }
        return null;

    }

    function egps_return_get_photo_data($data) {

        $album_data_array = EgpsAlbums::egps_get_one_photo($data['id']);

        return rest_ensure_response( $album_data_array );
    }
    
    function egps_return_get_photo_permission($data) {

        $album_data_array = get_option('egps_photometa');

        return rest_ensure_response( $album_data_array );
    }

    function egps_return_get_currency_and_price(){
        $data = get_option('egps_prices');

        if( $data != false ){
            $data["currencySetupCode"] = trim($data["currencySetupCode"]);
        }

        return rest_ensure_response($data);
    }

    function get_egps_photo_per_page(){
        $data = get_option('egps_sitedesign');

        return rest_ensure_response($data);
    }

    function egps_get_firebase_data(){
        $data = get_option('egps_firebase_options');
        $data['egps_site_url'] = site_url();

        return rest_ensure_response($data);
    }

    function egps_return_sum_price($data){
        $dataret = EgpsDatabase::egps_get_sum_price_from_db($data['email']); 

        return rest_ensure_response($dataret);
    }

    function egps_send_email_reg($data){

        $egps_email_opt = get_option('egps_email_options');

        $mailform = new EgpsEmailSend;
        $field_array = $mailform->egpsEmailGetFields();
        $dataout = $mailform->egpsEmailFieldData($egps_email_opt, $field_array);

        $dataret = $mailform->egpsEmailRegister( $data );

        return rest_ensure_response($dataret); //true or false
    }

    function egps_return_get_client_photos($data){
        $dataret = EgpsOrders::getCustomerAllOrders($data['email']); 

        return rest_ensure_response($dataret);
    }

    function egps_return_get_client_invoices($data){
        $dataret = EgpsOrders::getCustomerAllInvoices($data['email']); 

        return rest_ensure_response($dataret);
    }

    function egps_get_photo_production($data){

        $imgurl = EgpsOrders::egps_get_one_photo_by_gid($data['id']);

        return rest_ensure_response($imgurl);
    }

    function egps_inc_dwldcount($data){

        $imgurl = EgpsOrders::egps_inc_dwldcount($data['email'], $data['id']);

        return rest_ensure_response($imgurl);
    }

    function egps_get_order_details($data){

        $order = EgpsPayPal::egps_get_order_details($data['id']);

        return rest_ensure_response($order);
    }

    function egps_save_order_to_db($data){
        $dataret = EgpsPayPal::egps_save_order_to_db($data['email'], $data['id']); 

        return rest_ensure_response($dataret);
    }

    function egps_empty_cart_db($data){
        if(isset($data)){
            return EgpsDatabase::egps_delete_record_multiple("egps_cart", "customer_email", $data['email']);
        }
    }

    function egps_save_cart_to_db($data){
        if(isset($data)){

            $data_todb['customer_email'] = $data['email'];
            $data_todb['cart_items'] = $data['items'];
            $data_todb['text'] = $data['text'];
            $data_todb['time'] = date('Y-m-d');

            $retval = EgpsDatabase::egps_insert_to_db("egps_cart", $data_todb);

            if($retval != null){
                return rest_ensure_response( "ok" );
            }else{
                return null;
            }
        }
        return null;
    }

    function egps_get_pp_clientid($data){

        $dataout = get_option('egps_paypal_options')['paypal_client_id'];

        return rest_ensure_response( $dataout );
    }

    function egps_update_egps_lickey($data){

        if(!isset($data)){
            return rest_ensure_response( "error: empty data array." );
        }

        $egps_lic_opt = get_option('egps_license_options');

        if($egps_lic_opt['egps_api_key'] == $data['ak']){

            $opt_array = array(
                "egps_license_key" => $data['lk'],
                "egps_api_key" => $data['ak']
            );

            $ret = update_option("egps_license_options", $opt_array);

            return rest_ensure_response( $ret );

        }else{
            return rest_ensure_response( "error: API keys do not match." );
        }              

    }
    
    function egps_update_photometadata($data){

        if(!isset($data)){
            return rest_ensure_response( "error" );
        }

        $url_friendly_desc = Egps::egps_stripAccents($data["egps_desc"]);

        $datas = array(
            "egps_description" => $url_friendly_desc
        );

        // get photo egps_id for updating all photo's meta data with the same id
        $photodata = EgpsAlbums::egps_get_one_photo($data["egps_id"])[0];

        $where = array(
            "egps_id" => $photodata->egps_id
        );

        $saved = EgpsDatabase::egps_update_db_table("egps_photos", $datas, $where);
        EgpsDatabase::egps_update_tag_cloud( $url_friendly_desc, false ); //not increasing exsiting counts

        return rest_ensure_response(200);

    }
    

}

new EgpsREST();