<?php

namespace Blazemedia\Affiliation\PostSignature;


/**
 * PostSignature 
 * 
 * Crea una tabella di coppie chiave-valore in cui mappiamo le combinazioni
 * post_type / taxonomies che troviamo sul sito in corrispondenza di un certo post
 * 
 */
class PostSignatureTable {

    private static $instance;
    
    private $tableName = 'post_signature';
    private $tableFullName;
    private $db;

    private function __construct() {

        $this->db = $this->getDB();
    }

    private function getDB() {

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';

        global $wpdb;

        $charset_collate = $wpdb->get_charset_collate();
        
        $this->tableFullName = $wpdb->prefix . $this->tableName;

        $main_sql_create = <<<SQL
            CREATE TABLE  $this->tableFullName (
                `id` BIGINT(20) AUTO_INCREMENT PRIMARY KEY,
                `time` DATETIME,
                `key` TEXT
            );
        SQL;

        maybe_create_table( $wpdb->prefix . $this->tableName, $main_sql_create );

        $wpdb->access_table = $wpdb->prefix . $this->tableName;

        return $wpdb;
    }


    //register_uninstall_hook(__FILE__, 'e34s_db_clients_uninstall');
    function remove_table() {
        
        $sql = "DROP TABLE IF EXISTS $this->tableFullName";
        $this->db->query($sql);
        
        //delete_option('e34s_time_card_version');
    }

    
    /**
     * add a record
     *
     * @param string $key
     * @return int  - returns the new record's id
     */
    private function insert( string $key ) {

        $this->db->insert( 
            $this->tableFullName, 
            [
                'time' => current_time( 'mysql' ), 
                'key'  => $key
            ] 
        );

        return $this->select( $key );
    }

    private function delete( string $key ) {

        $this->db->delete( $this->tableFullName, [ 'key' => $key ] );
    }


    /**
     * Ritorna l'id della stringa corrispondente o false se non trova nulla
     *
     * @param string $key
     * @return int|bool
     */
    private function select( string $key ) {

        $query = "SELECT id FROM $this->tableFullName WHERE `key`='$key'";

        $result = $this->db->get_results( $query );

        if( $result == null ) return false;

        return (int) $result[0]->id;
    }


    public function getSignatureId( string $key ) {

        $id = $this->select( $key );
    
        return 'post_signature_' . ( $id === false ? $this->insert( $key ) : $id );
    }


    
    /**
     * Metodo pubblico per l'accesso all'istanza unica di classe.
     * @return object|
     */
    public static function getInstance() {

        if ( !isset( self::$instance ) ) {
            
            self::$instance = new PostSignatureTable();
        }
        
        return self::$instance;
    }



    
}
