<?php

require_once("db.php");

$codigoPre = $_GET['codigo_pre'];
$tipo   = $_GET['tipo'];
$idprod   = $_GET['idprod'];


// echo $idprod."#";

$query = "SELECT * FROM pre_pago where codigo = '$codigoPre' AND status = 1 ";
$result = mysql_query($query) or die(mysql_error);

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

if(mysql_num_rows($result) > 0){

    while ($row = mysql_fetch_assoc($result)) {
        echo $valor = $row['valor']."#";   
    }

    if ($num_rows == 0) {
        $query = "INSERT INTO creditos (idprod, data, valor, tipo) VALUES('$idprod', NOW(), '$valor', '$tipo')";
        $resultInsert = mysql_query($query);

        $queryPrePago = "UPDATE pre_pago SET status = 0 WHERE codigo = '$codigoPre'";
        $resultPrepago = mysql_query($queryPrePago);
    } else {
        
        $query = "UPDATE creditos SET data = NOW(), valor = '$valor',tipo = '$tipo', status = 1 WHERE idprod = '$idprod'";
        $resultInsert = mysql_query($query);

        $queryPrePago = "UPDATE pre_pago SET status = 0 WHERE codigo = '$codigoPre'";
        $resultPrepago = mysql_query($queryPrePago);
    }
    
} else {
    echo "null";
}

?>