<?php
include'database.php';

function userCreation(){
        $data = $_POST;
        $pdo = connectDatabase();
        createUser($pdo, $data);
        closeDatabase($pdo);
        header('location: user.php');
}

function userModification(){
        $data = $_POST;
        $id = $_POST["id"];
        $pdo = connectDatabase();
        editUser($pdo, $data, $id);
        closeDatabase($pdo);
        header('location: user.php');
}

function userDeletion(){
        $id = $_GET["delete"];
        $pdo = connectDatabase();
        deactivateUser($pdo, $data, $id);
        closeDatabase($pdo);
        header('location: user.php');
}

function userFind(){
        $data = $_POST;
        $pdo = connectDatabase();
        findUser($pdo, $data);
        closeDatabase($pdo);
        $search = $data["search_box"];
        header("location: user.php?search=$search");
}

function userLogin(){
        $location = 'login.php';
        $data = $_POST;
        $pdo = connectDatabase();
        $db_data = fetchLoginData($pdo, $data);
        closeDatabase($pdo);
        if($data["usuario"] == $db_data["usuario"] && $data["contraseña"] == $db_data["contraseña"]){
                session_start();
                $_SESSION["user"] = $db_data["usuario"]; 
                $_SESSION["user_type"] = $db_data["rol"]; 
                $location = 'index.php';
        }
        header("location: $location");
}

if (isset($_POST["create"])) {
    userCreation();
}


if (isset($_POST["edit"])) {
    userModification();
}

if (isset($_GET["delete"])) {
    userDeletion();
}

if (isset($_POST["search"])) {
    userFind();
}

if (isset($_POST["login"])) {
    userLogin();
}
