<?php
    header("Content-Type:application/json;");
    include("../connection.php");
    include("../utils.php");
    require '../../hooks/PHPMailer5/PHPMailerAutoload.php';
    
    // parametros obligatorios
    $parmsob = array("schoolidlist","datelist","accountlist","reflist","riflist","typelist","amountlist","sessionid",'due',"qtylist","currencyid", 'events', 'modalidad');
    if (!parametrosValidos($_GET, $parmsob))
        badEnd("400", array("msg"=>"Parametros obligatorios " . implode(", ", $parmsob)));
        
    //Inicializamos nuestras variables
    $out = new stdClass();
    $schoolid = $_GET["schoolidlist"];
    $account = explode('|',$_GET["accountlist"]);
    $date = date("Y-m-d",strtotime($_GET["datelist"]));
    $ref = explode('|',$_GET["reflist"]);
    $rif = explode('|',$_GET["riflist"]);
    $type = explode('|',$_GET["typelist"]);
    $amount = explode('|',$_GET["amountlist"]);
    $currency = explode('|',$_GET['currencyid']);
    $sessionid = $_GET["sessionid"];
    $due = $_GET['due'];
    $pupilqty = $_GET['qtylist'];
    $modalidad = $_GET['modalidad'];
    $events = $_GET['events'];
    
    //Validamos que la session sea valida para continuar
    isSessionValid($db, $sessionid);
    
    // Obtenemos los eventos
    $sql = "SELECT * FROM settings WHERE id = 8";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    $row= $rs->fetch_assoc();
    
    $events = $row['content'];
    
    // Obtenemos los datos del colegio
    $sql = "SELECT * FROM schools WHERE id = ".$schoolid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
    
    $schooldata= $rs->fetch_assoc();
    
    // COnsultamos para obtener si tenia pagos antes
    $sql = "SELECT COUNT(*) AS qty FROM payments WHERE schoolid = ".$schoolid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    $rowPay = $rs->fetch_assoc();
    
    for($i = 0; $i < sizeof($rif); $i++){
        //Insertamos los datos del pago
        $sql =  "INSERT INTO payments (schoolid, account, date, ref, rif, type, amount, currency, due, pupilqty) ".
        "       VALUES (".$schoolid.", ".
        "       '".$account[$i]."', ".
        "       '".$date."', ".
        "       '".$ref[$i]."', ".
        "       '".$rif[$i]."', ".
        "       ".$type[$i].", ".
        "       ".$amount[$i].", ".
        "       ".$currency[$i].", ".
        "       ".$due.", ".
        "       ".($i == 0 ? $pupilqty : 0).")";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error));
    }
    
    // Obtenemos que se hayan ingresado alumnos antes
    $sql = "SELECT allowedpupils FROM schools WHERE id = ".$schoolid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    $row = $rs->fetch_assoc();
    $allowedPupils = $row['allowedpupils'];
    
    if($rowPay['qty'] > 0){
        $sql = "UPDATE estimatedpupils SET ".
            "       qty = (qty + ".$pupilqty.") ".
            "       WHERE schoolid = ".$schoolid.
            "       AND level = 1 AND section = 'A'";
            if (!$db->query($sql))
                badEnd("500", array("msg"=>$db->error.$sql));
    } else {
        $sql = "INSERT INTO estimatedpupils (schoolid, level, section, qty) ".
        "       VALUES(".$schoolid.", 1, 'A', ".$pupilqty.")";
        if (!$db->query($sql))
            badEnd("500", array("msg"=>$db->error.$sql));
        
    }
    
    //En el primer pago bloqueamos el estimado
    $sql = "UPDATE schools SET ".
    "       estimatedpupilsedit = 0, ".
    "       ".($schooldata['events'] == null ? " events = '".$events."', " : '').
    "       ".($schooldata['modality'] == null ? " modality = '".$modalidad."', " : '').
    "       allowedpupils = (allowedpupils + ".$pupilqty.") ".
    "       WHERE schools.id =".$schoolid."";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$estimatedpupils));
        
    //Obtenemos los datos del colegio
    $sql = "SELECT name,region,email FROM schools WHERE id=".$schoolid;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row= $rs->fetch_assoc();
    $collegename = $row['name'];
    $region = $row['region'];
    $email = $row['email'];
    
    // Obtenemos los correos de notificaciones
    $sql = "SELECT content FROM settings WHERE id = 2";
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error));
        
    $row = $rs->fetch_assoc();
    
    $toemail = $email.",".implode(',',explode('|',$row['content']));
    
    //Obtenemos el total de alumnos estimados
    $sql ="SELECT MAX(pupilqty) as totally ".
    "       FROM payments ".
    "       WHERE schoolid=".$schoolid.
    "       AND DATE(date) = DATE('".$date."')".
    "       AND due = ".$due;
    if (!$rs=$db->query($sql))
        badEnd("500", array("msg"=>$db->error.$sql));
    
    //Ordenamos los datos para el correo de notificacion de pago
    $row = $rs->fetch_assoc();
    $estimatedpupils = $row['totally'];
    
    // Obtenemos las monedas
    foreach($currency as $curren){
        $currencyArr [] = $curren == 1 ? 'Bs.' : '$';
    }
    
    $from = "developer@totalsoftware.com.ve";
    $subject = "Pago Registrado  - ".$collegename;
    $subject = '=?UTF-8?B?'.base64_encode($subject).'?=';
            
    $body = "Se ha registrado un pago a trav&eacute;s de la p&aacute;gina web<br><br>".
            "<ul>".
            "<li>Colegio: ".$collegename."</li>".
            "<li>Regi&oacute;n: ".$region."</li>".
            "<li>Fecha: ".$date."</li>".
            "<li>Monto: ".implode (", ", $amount)."</li>".
            "<li>Moneda: ".implode(", ", $currencyArr)."</li>".
            "<li>Referencia: ".implode (", ", $ref)."</li>".
            "<li>Estimado de Alumnos: ".$estimatedpupils." Alumnos</li>".
            "<li>Estimado en $: ".$due."</li>".
            "</ul><br><br>".
            "<b>Olimp&iacute;adas Recreativas  de Matem&aacute;ticas</b>";
            
            
    //$toemail = "samuel_dear@hotmail.com,".$email;
    //, pmanager@totalsoftware.com.ve
    enviarCorreo($from, $toemail, $subject, $body);
    
    header("HTTP/1.1 200");
    echo (json_encode($out));
    die(); 
?>