<?php

namespace Blazemedia\Affiliation\Utils;

class ParseLinkLookUpTable {
   
    protected static $instance = null;

    protected $db;

    protected $mapping_table_name = 'gt_link_lookup_table';

    protected function __construct() {

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    
        $create_table = 
        "CREATE TABLE $this->mapping_table_name ( 
            id    INT AUTO_INCREMENT,
            link  VARCHAR(2048) NOT NULL, 
            PRIMARY KEY(id)
        );";

        maybe_create_table( $this->mapping_table_name, $create_table );

        global $wpdb;

        $this->db = $wpdb;
       
    }

    protected function getID( $link ) {

        return $this->db->get_results( "SELECT id FROM {$this->mapping_table_name} WHERE link = '{$link}'");
    }


    protected function save( $link ) : bool {
      
        $rows = $this->db->insert( $this->mapping_table_name, [ 'link' => $link ] );
        
        return $rows === false ? false : true;
    }

    
    public function getLinkId( $link ) {

        $link = urlencode( $link );

        $results = $this->getID( $link );

        if( empty($results) ) {

            $this->save( $link );
            
            $results =  $this->getID( $link );
        }

        if( empty($results) ) return 0;

        $result = array_shift($results);
        
        return $result->id;
    }


    public static function getInstance(){

        if( self::$instance == null ) {   

           $c = __CLASS__;
           self::$instance = new $c();
        }
        
        return self::$instance;
    }
    
}
