<?php

include('conexion.php');

CheckBD($db);

$error = '';

if (isset($_POST['Usuario']) && isset($_POST['Clave'])) {
    $Usuario = validate($_POST['Usuario']);
    $Clave = validate($_POST['Clave']);

    echo $Usuario . " / " . $Clave . "<br>";

    if (empty($Usuario) || empty($Clave)) {
        $error = '0';
    }

    $sqlVerificandoLogin = ("SELECT IdUser, nameUser, emailUser, passwordUser , UserAdmin FROM myusers WHERE emailUser ='" . $Usuario . "'");
    $resultLogin = mysqli_query($db, $sqlVerificandoLogin) or die(mysqli_error($con));
    $numLogin = mysqli_num_rows($resultLogin);

    echo $numLogin . "<br>";

    if ($numLogin > 0) {

        while ($rowData = mysqli_fetch_assoc($resultLogin)) {
            $passwordBD = $rowData['passwordUser'];
            if (password_verify($Clave, $passwordBD)) {
                echo "Usuario correcto". "<br>";

                session_start();
                $_SESSION['IdUser'] = $rowData['IdUser'];
                $_SESSION['nameUser'] = $rowData['nameUser'];
                $_SESSION['emailUser'] = $rowData['emailUser'];
                $_SESSION['UserAdmin'] = $rowData['UserAdmin'];

                echo $_SESSION['nameUser']. "<br>";

                header("location: ../main.php");
            }
        }
    } else {
        $error = '1';
    }
} else {
    $error = '-1';
}



function validate($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}    
