<?php

session_start();

include("../includes/auth.php");
include("../config/db.php");

$success = "";
$error = "";

/*
|--------------------------------------------------------------------------
| TABLAS
|--------------------------------------------------------------------------
*/

$conn->query("
CREATE TABLE IF NOT EXISTS roles (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS role_permissions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    role_id INT NOT NULL,
    permission_key VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

/*
|--------------------------------------------------------------------------
| VALIDAR role_id EN USERS
|--------------------------------------------------------------------------
*/

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

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

    $conn->query("
    ALTER TABLE users
    ADD COLUMN role_id INT NULL
    ");

}

/*
|--------------------------------------------------------------------------
| PERMISOS DISPONIBLES
|--------------------------------------------------------------------------
*/

$permissions = [

    'view_dashboard',
    'manage_users',
    'manage_campaigns',
    'manage_offices',
    'manage_fields',
    'view_reports',
    'manage_contracts',
    'manage_pipeline'

];

/*
|--------------------------------------------------------------------------
| CREAR ROL
|--------------------------------------------------------------------------
*/

if(
    $_SERVER['REQUEST_METHOD'] == 'POST'
    &&
    isset($_POST['create_role'])
){

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

    if($role_name != ''){

        $safe_name =
        $conn->real_escape_string($role_name);

        $conn->query("
        INSERT INTO roles
        (
            name
        )
        VALUES
        (
            '$safe_name'
        )
        ");

        $role_id =
        $conn->insert_id;

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

            foreach($_POST['permissions'] as $permission){

                $safe_permission =
                $conn->real_escape_string($permission);

                $conn->query("
                INSERT INTO role_permissions
                (
                    role_id,
                    permission_key
                )
                VALUES
                (
                    '$role_id',
                    '$safe_permission'
                )
                ");

            }

        }

        $success =
        "Rol creado correctamente.";

    } else {

        $error =
        "Debes ingresar un nombre para el rol.";

    }

}

/*
|--------------------------------------------------------------------------
| ACTUALIZAR PERMISOS
|--------------------------------------------------------------------------
*/

if(
    $_SERVER['REQUEST_METHOD'] == 'POST'
    &&
    isset($_POST['update_role_permissions'])
){

    $role_id =
    intval($_POST['role_id']);

    $conn->query("
    DELETE FROM role_permissions
    WHERE role_id = '$role_id'
    ");

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

        foreach($_POST['permissions'] as $permission){

            $safe_permission =
            $conn->real_escape_string($permission);

            $conn->query("
            INSERT INTO role_permissions
            (
                role_id,
                permission_key
            )
            VALUES
            (
                '$role_id',
                '$safe_permission'
            )
            ");

        }

    }

    $success =
    "Permisos actualizados correctamente.";

}

/*
|--------------------------------------------------------------------------
| ASIGNAR ROL A USUARIO
|--------------------------------------------------------------------------
*/

if(
    $_SERVER['REQUEST_METHOD'] == 'POST'
    &&
    isset($_POST['assign_role'])
){

    $user_id =
    intval($_POST['user_id']);

    $role_id =
    intval($_POST['role_id']);

    $conn->query("
    UPDATE users
    SET role_id = '$role_id'
    WHERE id = '$user_id'
    ");

    $success =
    "Rol asignado correctamente.";

}

/*
|--------------------------------------------------------------------------
| OBTENER ROLES
|--------------------------------------------------------------------------
*/

$roles =
$conn->query("
SELECT *
FROM roles
ORDER BY name ASC
");

/*
|--------------------------------------------------------------------------
| OBTENER USUARIOS
|--------------------------------------------------------------------------
*/

$users =
$conn->query("
SELECT
    users.*,
    roles.name AS role_name
FROM users
LEFT JOIN roles
ON users.role_id = roles.id
ORDER BY users.id DESC
");

?>

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

<head>

<meta charset="UTF-8">

<title>
Roles y permisos
</title>

<link rel="stylesheet" href="/assets/css/style.css">

<style>

.content-area{
    margin-left:260px;
    padding:40px;
}

.page-title{
    font-size:42px;
    font-weight:800;
    color:#02122c;
    margin-bottom:10px;
}

.page-subtitle{
    color:#64748b;
    margin-bottom:30px;
}

.white-card{
    background:#ffffff;
    border-radius:24px;
    padding:30px;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(15,23,42,.06);
}

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

.form-group label{
    display:block;
    margin-bottom:10px;
    font-weight:700;
    color:#334155;
}

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

.permissions-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(240px,1fr));
    gap:15px;
    margin-top:20px;
}

.permission-box{
    background:#f8fafc;
    border-radius:16px;
    padding:16px;
    display:flex;
    align-items:center;
    gap:10px;
}

.permission-box span{
    color:#02122c;
    font-weight:600;
    font-size:14px;
}

.btn-save{
    margin-top:25px;
    height:54px;
    border:none;
    border-radius:16px;
    padding:0 28px;
    background:linear-gradient(
        90deg,
        #5b4bff,
        #7b61ff
    );
    color:#ffffff;
    font-weight:700;
    cursor:pointer;
}

.role-item{
    padding:20px;
    border-radius:18px;
    background:#f8fafc;
    margin-bottom:20px;
}

.role-name{
    font-size:20px;
    font-weight:800;
    margin-bottom:15px;
    color:#02122c;
}

.permissions-list{
    display:flex;
    flex-wrap:wrap;
    gap:10px;
    margin-bottom:20px;
}

.permission-tag{
    background:#e0e7ff;
    color:#4338ca;
    padding:8px 14px;
    border-radius:999px;
    font-size:13px;
    font-weight:700;
}

.user-row{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:18px;
    border-radius:18px;
    background:#f8fafc;
    margin-bottom:15px;
    gap:20px;
}

.user-info{
    flex:1;
}

.user-name{
    font-size:17px;
    font-weight:800;
    color:#02122c;
    margin-bottom:5px;
}

.user-role{
    color:#64748b;
    font-size:14px;
}

.role-select{
    height:48px;
    border:none;
    border-radius:14px;
    background:#eef2ff;
    padding:0 14px;
    min-width:180px;
}

.assign-btn{
    height:48px;
    border:none;
    border-radius:14px;
    background:#02122c;
    color:#ffffff;
    padding:0 20px;
    font-weight:700;
    cursor:pointer;
}

.section-title{
    font-size:24px;
    font-weight:800;
    margin-bottom:25px;
    color:#02122c;
}

.success-box{
    background:#dcfce7;
    color:#166534;
    padding:15px;
    border-radius:14px;
    margin-bottom:20px;
}

.error-box{
    background:#fee2e2;
    color:#991b1b;
    padding:15px;
    border-radius:14px;
    margin-bottom:20px;
}

.empty-role{
    color:#94a3b8;
    font-size:14px;
}

.edit-role-box{
    margin-top:20px;
    border-top:1px solid #e2e8f0;
    padding-top:20px;
}

</style>

</head>

<body>

<?php include("../includes/sidebar.php"); ?>

<div class="content-area">

    <div class="page-title">
        Roles y permisos
    </div>

    <div class="page-subtitle">
        Configuraci¨®n de accesos del CRM
    </div>

    <?php if($success): ?>

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

    <?php endif; ?>

    <?php if($error): ?>

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

    <?php endif; ?>

    <div class="white-card">

        <div class="section-title">
            Crear rol
        </div>

        <form method="POST">

            <input
                type="hidden"
                name="create_role"
                value="1"
            >

            <div class="form-group">

                <label>
                    Nombre del rol
                </label>

                <input
                    type="text"
                    name="role_name"
                    class="form-control"
                    placeholder="Ejemplo: Supervisor"
                    required
                >

            </div>

            <div class="permissions-grid">

                <?php foreach($permissions as $permission): ?>

                    <div class="permission-box">

                        <input
                            type="checkbox"
                            name="permissions[]"
                            value="<?= $permission ?>"
                        >

                        <span>
                            <?= ucfirst(str_replace('_',' ',$permission)) ?>
                        </span>

                    </div>

                <?php endforeach; ?>

            </div>

            <button
                type="submit"
                class="btn-save"
            >
                Crear rol
            </button>

        </form>

    </div>

</div>

</body>
</html>