<?php 

class Emprestimos{

    public $id;
    public $nome;
    public $valor;
    public $motivo;

    public function emprestar(){
        global $database;

        if(isset($_POST['submitemprestimo'])){

            $this->nome = $_POST['nome'];
            $this->valor = $_POST['valor'];
            $this->motivo = $_POST['motivo'];
            
            $hora = date("H:i", mktime(gmdate("H")+2, gmdate("i"), gmdate("s"), gmdate("m"), gmdate("d"), gmdate("Y")));
            $user = $_SESSION['nome'];
            $now = date('Y-m-d');

            $sql = $database->query("INSERT INTO emprestimos(nome,valor,motivo,hora,data,usuario,status)
            VALUES('$this->nome','$this->valor','$this->motivo','$hora','$now','$user','pendente')");
            
            if($sql){
                $_SESSION['status'] = "Emprestimo concedido com sucesso";
                $_SESSION['status_code'] = "success";
                echo "<script>window.open('emprestimos.php','_self')</script>";
                    
                    
                }else{
                $_SESSION['status'] = "Ocorreu um erro";
                $_SESSION['status_code'] = "error";
                echo "<script>window.open('emprestimos.php','_self')</script>";
                }
        }
    }

    public function delete(){
        global $database;

        if(isset($_GET['delete']) && !empty($_GET['delete'])){
            
            $this->id = $_GET['delete'];

            $del = $database->query("DELETE FROM emprestimos WHERE id='$this->id'");
            if($del){
                $_SESSION['status'] = "Emprestimo eliminado com sucesso";
                $_SESSION['status_code'] = "success";
                echo "<script>window.open('emprestimos.php','_self')</script>";
                    
                    
                }else{
                $_SESSION['status'] = "Ocorreu um erro";
                $_SESSION['status_code'] = "error";
                echo "<script>window.open('emprestimos.php','_self')</script>";
                }
        }
    }

    public function payEmprestimo(){
        global $database;

        if(isset($_GET['pagar']) && !empty($_GET['pagar'])){
            
            $this->id = $_GET['pagar'];

            $pay = $database->query("UPDATE emprestimos SET status ='pago' WHERE id='$this->id'");
            if($pay){
                $_SESSION['status'] = "Emprestimo eliminado com sucesso";
                $_SESSION['status_code'] = "success";
                echo "<script>window.open('emprestimos.php','_self')</script>";
                    
                    
                }else{
                $_SESSION['status'] = "Ocorreu um erro";
                $_SESSION['status_code'] = "error";
                echo "<script>window.open('emprestimos.php','_self')</script>";
                }
        }
    }


}
$emprestimo = new Emprestimos();

?>