<?php

session_start();

include 'config/db.php';

/*
|--------------------------------------------------------------------------
| CREAR COLUMNAS DE PERMISOS SI NO EXISTEN
|--------------------------------------------------------------------------
*/

$permissions = [

    'can_view_dashboard',

    'can_view_leads',
    'can_create_leads',
    'can_edit_leads',

    'can_view_contracts',
    'can_create_contracts',
    'can_edit_contracts',
    'can_export_contracts',

    'can_view_pipeline',

    'can_view_campaign_metrics',
    'can_view_team_metrics',
    'can_view_office_metrics',
    'can_view_reports',

    'can_manage_users',
    'can_manage_campaigns',
    'can_manage_offices',
    'can_manage_custom_fields'

];

foreach($permissions as $permission){

    $check_column = $conn->query("
    SHOW COLUMNS
    FROM users
    LIKE '$permission'
    ");

    if($check_column->num_rows == 0){

        $conn->query("
        ALTER TABLE users
        ADD COLUMN $permission TINYINT(1) DEFAULT 0
        ");

    }

}

/*
|--------------------------------------------------------------------------
| REDIRECT SI YA LOGUEADO
|--------------------------------------------------------------------------
*/

if(isset($_SESSION['user_id'])){

    header("Location: /pages/dashboard.php");
    exit;

}

$error = "";

/*
|--------------------------------------------------------------------------
| LOGIN
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $email =
    trim($_POST['email']);

    $password =
    trim($_POST['password']);

    if(
        empty($email) ||
        empty($password)
    ){

        $error =
        "Completa todos los campos.";

    } else {

        $stmt = $conn->prepare("
        SELECT *
        FROM users
        WHERE email = ?
        LIMIT 1
        ");

        $stmt->bind_param(
            "s",
            $email
        );

        $stmt->execute();

        $result =
        $stmt->get_result();

        if ($result->num_rows > 0) {

            $user =
            $result->fetch_assoc();

            if (
                password_verify(
                    $password,
                    $user['password']
                )
            ) {

                session_regenerate_id(true);

                /*
                |--------------------------------------------------------------------------
                | GUARDAR USER EN SESSION
                |--------------------------------------------------------------------------
                */

                foreach($user as $key => $value){

                    $_SESSION[$key] = $value;

                }

                /*
                |--------------------------------------------------------------------------
                | SESSION PRINCIPAL
                |--------------------------------------------------------------------------
                */

                $_SESSION['user_id'] =
                $user['id'];

                $_SESSION['user_name'] =
                isset($user['name'])
                ? $user['name']
                : 'Usuario';

                $_SESSION['user_email'] =
                $user['email'];

                /*
                |--------------------------------------------------------------------------
                | VISUAL ROLE
                |--------------------------------------------------------------------------
                */

                $_SESSION['visual_role'] =
                isset($user['visual_role'])
                ? $user['visual_role']
                : '';

                /*
                |--------------------------------------------------------------------------
                | LOGIN
                |--------------------------------------------------------------------------
                */

                $_SESSION['logged_in'] =
                true;

                header(
                    "Location: /pages/dashboard.php"
                );

                exit;

            } else {

                $error =
                "Contraseña incorrecta.";

            }

        } else {

            $error =
            "Usuario no encontrado.";

        }

    }

}

?>

<!DOCTYPE html>
<html lang="es">

<head>

<meta charset="UTF-8">

<meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
>

<title>
Wolfxell CRM
</title>

<style>

*{
    box-sizing:border-box;
}

body{
    margin:0;
    font-family:Arial,sans-serif;
    background:
    linear-gradient(
        135deg,
        #071226,
        #111827,
        #1e1b4b
    );
    min-height:100vh;
    display:flex;
    justify-content:center;
    align-items:center;
    padding:30px;
}

.login-wrapper{
    width:100%;
    max-width:460px;
}

.login-box{
    width:100%;
    background:#ffffff;
    border-radius:28px;
    padding:45px;
    box-shadow:
    0 25px 60px rgba(0,0,0,.25);
}

.logo{
    font-size:34px;
    font-weight:900;
    color:#5b4bff;
    text-align:center;
    margin-bottom:12px;
    letter-spacing:1px;
}

.subtitle{
    text-align:center;
    color:#64748b;
    margin-bottom:35px;
    font-size:15px;
}

.form-group{
    margin-bottom:18px;
}

.form-label{
    display:block;
    margin-bottom:10px;
    font-size:14px;
    font-weight:700;
    color:#0f172a;
}

.form-control{
    width:100%;
    height:56px;
    border:none;
    background:#f3f5fa;
    border-radius:16px;
    padding:0 18px;
    font-size:15px;
    outline:none;
}

.form-control:focus{
    background:#eef2ff;
}

.btn-login{
    width:100%;
    height:56px;
    border:none;
    border-radius:16px;
    background:
    linear-gradient(
        90deg,
        #5b4bff,
        #7b61ff
    );
    color:#ffffff;
    font-size:16px;
    font-weight:700;
    cursor:pointer;
    margin-top:10px;
}

.error-box{
    background:#fee2e2;
    color:#991b1b;
    padding:14px 18px;
    border-radius:14px;
    margin-bottom:22px;
    font-size:14px;
    font-weight:600;
    text-align:center;
}

.footer-text{
    text-align:center;
    margin-top:25px;
    font-size:13px;
    color:#94a3b8;
}

</style>

</head>

<body>

<div class="login-wrapper">

    <div class="login-box">

        <div class="logo">
            WOLFXELL CRM
        </div>

        <div class="subtitle">
            Plataforma de gestión comercial y contratos
        </div>

        <?php if($error != ""): ?>

            <div class="error-box">
                <?= $error ?>
            </div>

        <?php endif; ?>

        <form method="POST">

            <div class="form-group">

                <label class="form-label">
                    Correo electrónico
                </label>

                <input
                    type="email"
                    name="email"
                    class="form-control"
                    placeholder="correo@empresa.com"
                    required
                >

            </div>

            <div class="form-group">

                <label class="form-label">
                    Contraseña
                </label>

                <input
                    type="password"
                    name="password"
                    class="form-control"
                    placeholder="••••••••••"
                    required
                >

            </div>

            <button
                type="submit"
                class="btn-login"
            >
                Iniciar sesión
            </button>

        </form>

        <div class="footer-text">
            Wolfxell CRM © <?= date('Y') ?>
        </div>

    </div>

</div>

</body>
</html>