<?php
// class-records.php

class records {

	private $query;

	public function __construct() {
		$this->query = new query;
		$this->session = Session::getInstance();
	}

	public function get_record($record, $cache = true, $expiry = 300) {
		if($cache && isset($this->session->{"records_".$record})) {
			if($this->session->{"recordTS_".$record} + $expiry > time()) {
				return $this->session->{"records_".$record};
			}
		}
		$existing_record = $this->record_exists($record);
		if(!$existing_record) {
			return false;
		}
		foreach ($existing_record as $key => $value) {
			$record_value = $value['record_value'];
		}
		if(is_serialized($record_value)) {
			$record_value = unserialize($record_value);
		}
		if($cache) {
			$this->session->{"records_".$record} = $record_value;
			$this->session->{"recordTS_".$record} = time();
		}
		return $record_value;
	}

	public function update_record($record, $record_value) {
		$record = strtolower($record);
		do_action("before_update_".$record, ['record_value' => $record_value]);
		$existing_record = $this->record_exists($record);
		if($existing_record) {
			foreach ($existing_record as $key => $value) {
				$id = $key;
				break;
			}
			//update record
			if(isset($this->session->{"records_".$record})) {
				$this->session->{"records_".$record} = $record_value;
				$this->session->{"recordTS_".$record} = time();
			}
			
			if(is_array($record_value)){
				$record_value = serialize($record_value);
			}
			return $this->query->update( 'records', array('record_value' => $record_value), array('id' => $id));
		}
		//add_record
		if(isset($this->session->{"records_".$record})) {
			$this->session->{"records_".$record} = $record_value;
			$this->session->{"recordTS_".$record} = time();
		}
		return $this->add_record($record, $record_value);
	}

	public function record_exists($record) {
		return $this->query->quick_select('records', ["where" => ['record_name' => $record], "compare" => "LIKE"], ARRAY_A);
	}

	public function add_record($record, $record_value) {
		$record = strtolower($record);
		do_action("before_add_".$record, ['theme' => $record_value]);
		if(is_array($record_value)){
			$record_value = serialize($record_value);
		}
		return $this->query->insert('records', array('record_name', 'record_value'), array($record, $record_value));
	}

	public function remove_record($record) {
		$existing_record = $this->record_exists($record);
		if(! $existing_record) {
			return false;
		}
		foreach ($existing_record as $key => $value) {
			if(isset($this->session->{"recordTS_".$value['record_name']})) {
				$this->session->{"recordTS_".$value['record_name']} = 0;
			}
			$this->query->delete('records', array('id' => $value['id']));
		}
		return;
	}
}