<?php

/**
 * Developer: Iaax Page (twitter.com/iaaxpage)
 * Date: 9/8/15, 2:59 PM
 * Generator: PhpStorm
 */
namespace OctopusSignatureClient\WordPress;
// TODO: Add dependencies USE statemens here

use OctopusSignatureClient\Commons\WebRequest;

class CustomAPI
{

    public function __construct()
    {
        $this->registerFilters()->addRewriteRules();
    }

    private function registerFilters()
    {
        // Queryvars Filter
        add_filter( 'query_vars', array( __CLASS__, 'addCustomQueryVarsFilter' ) );
        // Parse Request
        add_filter( 'parse_request', array( __CLASS__, 'parseRequestFilter' ) );

        return $this;
    }

    private function addRewriteRules()
    {
//        add_rewrite_tag( '%client_website_id%', '([0-9]+)' );
        add_rewrite_rule( 'octopus-signature-client-api/([0-9]+)/?$', 'index.php?octopus-client-signature=1&client_website_id=$matches[1]', 'top' );
        flush_rewrite_rules();
        return $this;
    }

    // Static Methods

    private static function answerPing($websiteID)
    {
        header('Content-type: application/json');
        if( $currentWebsiteID = get_site_option( 'client_website_id', $websiteID ) ){
            // Save the website ID
            if( $currentWebsiteID != $websiteID ){
                update_site_option( 'client_website_id', $websiteID );
            }
        }

        // Get signature information and Persist data
        $requestTarget = "http://octopus.mx/octopus-signature-api/{$websiteID}";
        $request = WebRequest::curlThis( $requestTarget, array() );

        if( intval( $request['code'] ) == 200 ){
            $clientData = json_decode( $request['response'] );
            update_site_option( 'signature_style_url', $clientData->cssURL );
            update_site_option( 'signature_pages_list', $clientData->pages );
            echo json_encode( array( 'status' => 'ok', 'siteURL' => $clientData->url, 'siteID' => $clientData->ID ) );
            die();
        }

        echo json_encode( array( 'status' => 'failed', 'siteID' => $websiteID, 'targetURL' => $requestTarget, 'code' => $request['code'] ) );
        die();
    }

    public static function parseRequestFilter()
    {
        global $wp;
        if( isset( $wp->query_vars['octopus-client-signature'] ) ){
            self::answerPing( $wp->query_vars['client_website_id'] );
            exit;
        }
    }

    public static function addCustomQueryVarsFilter( $queryVars )
    {
        $queryVars[] = 'octopus-client-signature';
        $queryVars[] = 'client_website_id';
        return $queryVars;
    }


    public static function removeEndPoint()
    {
        flush_rewrite_rules();
    }

}