<?php
class Calendarista_UpdatesController extends Calendarista_BaseController{
	public function __construct($updateCallback, $deleteCallback){
		if (!(array_key_exists('controller', $_POST) 
			&& $_POST['controller'] == 'calendarista_updates')){
				return;
		}
		if(!Calendarista_NonceHelper::valid()){
			return;
		}
		parent::__construct(null, $updateCallback, $deleteCallback);
	}
	public function update($callback){
		if (Calendarista_NetworkHelper::isLocalhost()){
			$result = -2;
		}else{
			$repo = new Calendarista_GeneralSettingsRepository();
			$generalSetting = $repo->read();
			$purchaseCode = trim($_POST['purchaseCode']);
			$result = Calendarista_UpdatesRequestHelper::verify($purchaseCode);
			if(!in_array($result, array(-1, 0))){
				$generalSetting->purchaseCode = sanitize_text_field($_POST['purchaseCode']);
				if($generalSetting->id === -1){
					$repo->insert($generalSetting);
				}else{
					$repo->update($generalSetting);
				}
				$result = 2;
			}
		}
		$this->executeCallback($callback, array($result));
	}
	public function delete($callback){
		$repo = new Calendarista_GeneralSettingsRepository();
		$generalSetting = $repo->read();
		Calendarista_UpdatesRequestHelper::test($generalSetting->purchaseCode);
		$generalSetting->purchaseCode = '';
		$result = $repo->update($generalSetting);
		$this->executeCallback($callback, array($result));
	}
}
?>