<?php
session_start();
require_once('../../BDD/SqliteDb.php');

$db = new SqliteDb('save');


$question = str_replace("textbox","", $_GET['id']);
$tab = explode('-', $question);

$numQcm = $tab[0];
$numQuestion = $tab[1]; 
$numReponse =  $tab[2];

//$user = "mehdi";
$user = $_SERVER['REMOTE_USER'];


if($_GET['type'] == 'vraifaux'){
    if($_GET['check'] == 'true'){
        $query = $db->prepare('INSERT OR REPLACE INTO QcmSauvegarde  VALUES (?,?,?,?)');      
        $query->bindParam(1, $user);
        $query->bindParam(2,$numQcm);
        $query->bindParam(3,$numQuestion);
        $query->bindParam(4,$numReponse);
        $result = $query->execute();
        echo "d";
    }
    else {
        $query = $db->prepare('DELETE FROM  QcmSauvegarde WHERE numQcm=? AND numQuestion=? AND numReponse = ? AND idEtudiant=?');        
        $query->bindParam(1,$numQcm);
        $query->bindParam(2,$numQuestion);
        $query->bindParam(3,$numReponse);
        $query->bindParam(4, $user);
        $result = $query->execute();
        echo "e";
    }
}
else {
    //Sauvegarde des notes//
    $query = $db->prepare('SELECT points FROM QcmReponse WHERE numQuestion=? AND numQcm= ? AND numReponse= ?');
    $query->bindParam(1, $numQuestion);
    $query->bindParam(2, $numQcm);
    $query->bindParam(3,$numReponse);
    $result = $query->execute();
    $pointRow = $result->fetchArray();
    
    $query = $db->prepare('INSERT OR REPLACE INTO NotesParQuestion  VALUES (?,?,?,?)');        
    $query->bindParam(1,$user);
    $query->bindParam(2,$numQcm);
    $query->bindParam(3,$numQuestion);
    $query->bindParam(4,$pointRow['points']);
    $result = $query->execute();
    
    $query = $db->prepare('SELECT note FROM NotesParQuestion WHERE numQcm= ? AND idEtudiant = ?');
    $query->bindParam(1, $numQcm);
    $query->bindParam(2, $user);
    $result = $query->execute();

    $note = 0;
    while($r = $result->fetchArray()){
        $note += $r['note'];
    }

    $query = $db->prepare('INSERT OR REPLACE INTO Notes  VALUES (?,?,?)');
    $query->bindParam(1,$user );
    $query->bindParam(2,$numQcm);
    $query->bindParam(3,$note );
    $result = $query->execute();

    
    
    //Sauvegarde des REPONSES//    
    $query = $db->prepare('DELETE FROM QcmSauvegarde WHERE numQcm= ? AND numQuestion = ? AND idEtudiant=?');        
    $query->bindParam(1,$numQcm);
    $query->bindParam(2,$numQuestion);
    $query->bindParam(3, $user);
    $result = $query->execute();
    
    $query = $db->prepare('INSERT OR REPLACE INTO QcmSauvegarde  VALUES (?,?,?,?)');        
    $query->bindParam(1, $user);
    $query->bindParam(2,$numQcm);
    $query->bindParam(3,$numQuestion);
    $query->bindParam(4,$numReponse);
    $result = $query->execute();
    
    //$db->ecrireFichierNotes($numQcm,'save');

                               
}

