<?php

    require "mysql_config.php";

    $json = json_decode(file_get_contents('php://input'));
    var_dump($json);
    $id = $json->{'results'}[0]->{'recid'};


    $success = $json->{'results'}[0]->{'success'};
    switch($json->{'nonce'}){
        case "FFT":
			if($json->{'results'}[0]->{'success'} == "true"){
				$conn->query("UPDATE gorazd_editor.editor_cache SET `fft`='1' WHERE `id`='$id'");
			}else{
				$conn->query("UPDATE gorazd_editor.editor_cache SET `fft`='3' WHERE `id`='$id'");
			}
			file_put_contents('logs/post_dump'.$id.'_ftt.txt', file_get_contents('php://input'));
            break;
        case "MARC":
            if($json->{'results'}[0]->{'success'} == "true"){
				$conn->query("UPDATE gorazd_editor.editor_cache SET `marc`='1' WHERE `id`='$id'");
			}else{
				$conn->query("UPDATE gorazd_editor.editor_cache SET `marc`='3' WHERE `id`='$id'");
			}
			file_put_contents('logs/post_dump'.$id.'_marc.txt', file_get_contents('php://input'));
            break;
        case "FIX":
            if($json->{'results'}[0]->{'success'} == "true"){
				$conn->query("UPDATE gorazd_editor.editor_cache SET `fix`='1' WHERE `id`='$id'");
			}else{
				$conn->query("UPDATE gorazd_editor.editor_cache SET `fix`='3' WHERE `id`='$id'");
			}
			file_put_contents('logs/post_dump'.$id.'_fix.txt', file_get_contents('php://input'));
            break;
    }
	file_put_contents('logs/post_dump'.$id.'_last.txt', file_get_contents('php://input'));
    $sql = "SELECT fft, marc, fix FROM `editor_cache` WHERE `id`='$id' ORDER BY time DESC LIMIT 1";
    $result = $conn->query($sql);
    if($result->num_rows > 0){
            $result = $result->fetch_assoc();
	    if($result['fft'] == "1" && $result['marc'] == "1" && $result['fix'] == "1"){
	        $conn->query("DELETE FROM gorazd_editor.editor_cache WHERE `id`='$id'");
	    }else{
			if($result['fft'] != "0" && $result['marc'] != "0" && $result['fix'] != "0"){
				$sql = "UPDATE gorazd_editor.editor_cache SET `status`='error' WHERE `id`='$id'";
				$conn->query($sql);
			}
	    }
	}else{

	}
    function writeToMainLog($msg,$tp){
       $type;
       switch($tp){
                case "1":
                   $type = "inf";
                   break;
                case "2":
                   $type = "wrn";
                   break;
                case "3":
                   $type = "err";
                   break;
       }
       $date = date("Y-m-d H:i:s");
       $log  = $date." | type:".$type." | msg:".$msg.PHP_EOL;
       file_put_contents("main_log.txt", $log , FILE_APPEND);
    }

?>
