<?php

$filename = 'c_leitura.php';
session_start();
if (!file_exists($filename)) {
    header("Location: error.php");
    exit;
}

include 'c_leitura.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . "sealed" . DIRECTORY_SEPARATOR . "autoload.php";
register_shutdown_function('FUNCOES::fatalErrorHandler');

include ('db.php');

if (!empty($_POST['valor'])) {
    $valor = $_POST['valor'];
} else {
    $valor = -7;
}

$idprod = $_POST['idprod'];
$tipo = $_POST['tipo'];

$query = "SELECT id FROM creditos WHERE idprod = '$idprod' ORDER BY data DESC LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
$num_rows = mysql_num_rows($result);
$data = date("Y-m-d H:i:s");

try {
    if ($num_rows == 0) {
        $query = "INSERT INTO creditos (idprod, data, valor, tipo) VALUES('$idprod', NOW(), '$valor', '$tipo')";
        $resultInsert = mysql_query($query);
    } else {
        $query = "UPDATE creditos SET data = NOW(), valor = '$valor',tipo = '$tipo', status = 1 WHERE idprod = '$idprod'";
        $resultInsert = mysql_query($query);
    }

    if ($resultInsert) {
        echo json_encode(array('success' => 1, 'idprod' => $idprod));
        exit;
    } else {
        echo json_encode(array('success' => 0, 'msg' => 'Ocorreu um erro ao inserir créditos'));
        exit;
    }
    exit;
} catch (Exception $err) {
    FUNCOES::logMsg($err->getMessage(), 'error', 'logs/error/error_'.date("Y-m-d").'.log');
    echo json_encode(array('success' => 0, 'msg' => $err->getMessage()));
}
exit;
?>