<?php 

class resultPin {

    private $query;

    public function __construct() {
    	$this->query = new query;
    }

    public function randomPin() {
    	$st1 = rand(10000, 99999);
    	$st2 = rand(10000, 99999);
    	$st3 = rand(10000, 99999);
    	return $st1.$st2.$st3;
    }

    private function pin_unique($pin) {
    	$query = $this->query->select('result_pins', array('pin' => $pin), 0, 'ASC', 0, 'LIKE');
		$result = $this->query->query_to_array($query);
		if(!empty($result)) {
			return false;
		} else return true;
    }

    public function add_pin($batch = '') {
    	if($batch == '')
    		$batch = 'B-'.time();
    	do {
    		$pin = $this->randomPin();
    		$pin_unique = $this->pin_unique($pin);
    	} while(!$pin_unique);

    	$ins =$this->query->insert(
		    			'result_pins',
						['pin', 'batch', 'valid'],
						[$pin, $batch, 1]
						);
    	return $ins;
    }

    public function update_pin_meta($id, $meta) {
    	$id = (int) $id;
    	if(isset($meta['id']))
    		unset($meta['id']);
    	if(isset($meta['pin']))
    		unset($meta['pin']);
    	if(isset($meta['batch']))
    		unset($meta['batch']);
    	$result = $this->query->update( 'result_pins', $meta, ['id' => $id] );
    	return $result;
    }

    public function generate_pins($count) {
    	$post = new post;
    	$batch = 'B-'.time();
    	for ($i=0; $i < $count; $i++) { 
    		$this->add_pin($batch);
    	}
    	$args = [
    		'type' => 'result_pins',
    		'batch' => $batch,
    		'count' => $count
    	];
    	$post->add_post($args);
    }

    public function get_pins_by_meta_data($meta) {
    	$pins_data = $this->query->query_to_array($this->query->select('result_pins', $meta, 0, $sort, $limit, 'LIKE'));
    	return $pins_data;
    }

    public function format_pin($pin) {
    	$pin_arr = str_split($pin, 4);
    	$var = "";
    	foreach ($pin_arr as $seg) {
    		$var .= $seg.' ';
    	}
    	return $var;
    }

    public function verify_pin($pin) {
    	if(!is_string($pin)) {
    		$pin = sprintf('%.0f', $pin);
    	}
    	$pin = trim($pin);
    	$pin = str_replace(' ', '', $pin);
    	$pin = str_replace('-', '', $pin);
    	$res = $this->get_pins_by_meta_data(['pin' => $pin]);
    	if(_count($res) > 0) {
    		return array_shift($res);
    	} else {
    		return false;
    	}
    }

    public function invalidate_pin($pin) {
    	$pin_meta = $this->verify_pin($pin);
    	if($pin_meta) {
    		return $this->update_pin_meta($pin_meta['id'], ['valid' => 0]);
    	}
    }

    public function validate_pin($pin) {
    	$pin_meta = $this->verify_pin($pin);
    	if($pin_meta) {
    		return $this->update_pin_meta($pin_meta['id'], ['valid' => 1]);
    	}
    }

    public function is_valid($pin) {
    	$pin = $this->verify_pin($pin);
    	if($pin) {
    		if($pin['valid'] == 1) {
    			return $pin;
    		} else {
    			return false;
    		}
    	} else {
    		return false;
    	}
    }
}