<?php

session_start();

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

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

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

if(
    !isset($_SESSION['can_manage_users'])
    ||
    intval($_SESSION['can_manage_users']) !== 1
){
    die("No tienes permisos para acceder a esta sección.");
}

/*
|--------------------------------------------------------------------------
| ASEGURAR COLUMNA VISUAL_ROLE
|--------------------------------------------------------------------------
*/

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

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

    $conn->query("
    ALTER TABLE users
    ADD COLUMN visual_role VARCHAR(100) NULL AFTER role
    ");

}

/*
|--------------------------------------------------------------------------
| TABLA ROLES VISUALES
|--------------------------------------------------------------------------
*/

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

/*
|--------------------------------------------------------------------------
| ROLES VISUALES DEFAULT
|--------------------------------------------------------------------------
*/

$default_roles = [
    'Dueño Franquicia',
    'Supervisor',
    'Líder',
    'Asesor',
    'Admin'
];

foreach($default_roles as $default_role){

    $safe_role =
    $conn->real_escape_string($default_role);

    $checkRole = $conn->query("
    SELECT id
    FROM visual_roles
    WHERE role_name = '$safe_role'
    LIMIT 1
    ");

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

        $conn->query("
        INSERT INTO visual_roles
        (
            role_name
        )
        VALUES
        (
            '$safe_role'
        )
        ");

    }

}

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

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

$conn->query("
CREATE TABLE IF NOT EXISTS offices (
    id INT AUTO_INCREMENT PRIMARY KEY,
    office_name VARCHAR(255),
    office_city VARCHAR(255),
    status ENUM('active','inactive') DEFAULT 'active',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255),
    email VARCHAR(255) UNIQUE,
    password VARCHAR(255),

    role VARCHAR(100) NULL,

    visual_role VARCHAR(100) NULL,

    leader_id INT NULL,

    office_id INT NULL,

    is_active TINYINT(1) DEFAULT 1,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS user_campaigns (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    campaign_id INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS user_offices (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    office_id INT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

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

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

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

    if($role_name == ""){

        $error =
        "Debes ingresar el nombre del rol.";

    } else {

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

        $exists = $conn->query("
        SELECT id
        FROM visual_roles
        WHERE role_name = '$safe_role'
        LIMIT 1
        ");

        if($exists->num_rows > 0){

            $error =
            "Ese rol visual ya existe.";

        } else {

            $stmt = $conn->prepare("
            INSERT INTO visual_roles
            (
                role_name
            )
            VALUES (?)
            ");

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

            $stmt->execute();

            $success =
            "Rol visual creado correctamente.";

        }

    }

}

/*
|--------------------------------------------------------------------------
| ELIMINAR ROL VISUAL
|--------------------------------------------------------------------------
*/

if(isset($_GET['delete_visual_role'])){

    $role_id =
    intval($_GET['delete_visual_role']);

    $roleQuery = $conn->query("
    SELECT role_name
    FROM visual_roles
    WHERE id = '$role_id'
    LIMIT 1
    ");

    if($roleQuery && $roleQuery->num_rows > 0){

        $roleData =
        $roleQuery->fetch_assoc();

        $roleName =
        $conn->real_escape_string(
            $roleData['role_name']
        );

        $conn->query("
        UPDATE users
        SET visual_role = NULL
        WHERE visual_role = '$roleName'
        ");

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

    }

    header("Location: settings_users.php");
    exit;

}

/*
|--------------------------------------------------------------------------
| ACTIVAR / DESACTIVAR USUARIO
|--------------------------------------------------------------------------
*/

if(isset($_GET['toggle_user'])){

    $toggle_user_id =
    intval($_GET['toggle_user']);

    if($toggle_user_id != $_SESSION['user_id']){

        $userQuery = $conn->query("
        SELECT is_active
        FROM users
        WHERE id = '$toggle_user_id'
        LIMIT 1
        ");

        if($userQuery && $userQuery->num_rows > 0){

            $userData =
            $userQuery->fetch_assoc();

            $newStatus =
            $userData['is_active'] == 1
            ? 0
            : 1;

            $conn->query("
            UPDATE users
            SET is_active = '$newStatus'
            WHERE id = '$toggle_user_id'
            ");

        }

    }

    header("Location: settings_users.php");
    exit;

}

/*
|--------------------------------------------------------------------------
| CREAR USUARIO
|--------------------------------------------------------------------------
*/

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

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

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

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

    $visual_role =
    trim($_POST['visual_role'] ?? '');

    $leader_id =
    intval($_POST['leader_id'] ?? 0);

    $offices =
    $_POST['offices'] ?? [];

    $campaigns =
    $_POST['campaigns'] ?? [];

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

        $error =
        "Completa todos los campos obligatorios.";

    } else {

        $check = $conn->query("
        SELECT id
        FROM users
        WHERE email = '".$conn->real_escape_string($email)."'
        LIMIT 1
        ");

        if($check->num_rows > 0){

            $error =
            "El correo ya existe.";

        } else {

            $hashed =
            password_hash(
                $password,
                PASSWORD_DEFAULT
            );

            $stmt = $conn->prepare("
                INSERT INTO users
                (
                    name,
                    email,
                    password,
                    visual_role,
                    leader_id
                )
                VALUES (?, ?, ?, ?, ?)
            ");

            $stmt->bind_param(
                "ssssi",
                $name,
                $email,
                $hashed,
                $visual_role,
                $leader_id
            );

            if($stmt->execute()){

                $user_id =
                $stmt->insert_id;

                /*
                |--------------------------------------------------------------------------
                | GUARDAR OFICINAS
                |--------------------------------------------------------------------------
                */

                foreach($offices as $office_id){

                    $office_id =
                    intval($office_id);

                    $saveOffice =
                    $conn->prepare("
                    INSERT INTO user_offices
                    (
                        user_id,
                        office_id
                    )
                    VALUES (?, ?)
                    ");

                    $saveOffice->bind_param(
                        "ii",
                        $user_id,
                        $office_id
                    );

                    $saveOffice->execute();

                }

                /*
                |--------------------------------------------------------------------------
                | GUARDAR CAMPAÑAS
                |--------------------------------------------------------------------------
                */

                foreach($campaigns as $campaign_id){

                    $campaign_id =
                    intval($campaign_id);

                    $saveCampaign =
                    $conn->prepare("
                    INSERT INTO user_campaigns
                    (
                        user_id,
                        campaign_id
                    )
                    VALUES (?, ?)
                    ");

                    $saveCampaign->bind_param(
                        "ii",
                        $user_id,
                        $campaign_id
                    );

                    $saveCampaign->execute();

                }

                $success =
                "Usuario creado correctamente.";

            } else {

                $error =
                "Error al crear usuario.";

            }

        }

    }

}

/*
|--------------------------------------------------------------------------
| LISTADOS
|--------------------------------------------------------------------------
*/

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

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

$offices = $conn->query("
SELECT *
FROM offices
WHERE status = 'active'
ORDER BY office_name ASC
");

$current_user_id =
intval($_SESSION['user_id']);

$visibleUsers =
getVisibleUsers(
    $conn,
    $current_user_id
);

$visibleUsersSql =
visibleUsersToSql(
    $conn,
    $_SESSION['user_id']
);

$users = $conn->query("
SELECT *
FROM users
WHERE id IN ($visibleUsersSql)
ORDER BY id DESC
");

$visualRoles = $conn->query("
SELECT *
FROM visual_roles
ORDER BY role_name ASC
");

?>

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

<head>

<meta charset="UTF-8">

<title>
Usuarios
</title>

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

<style>

.content-area{
    margin-left:260px;
    padding:40px;
}
.top-actions{
    margin-bottom:25px;
}

.back-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:46px;
    padding:0 18px;
    border-radius:14px;
    background:#e2e8f0;
    color:#02122c;
    text-decoration:none;
    font-size:14px;
    font-weight:700;
}

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

.page-subtitle{
    font-size:16px;
    color:#6b7280;
    margin-bottom:30px;
}

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

.form-grid{
    display:grid;
    grid-template-columns:
    repeat(auto-fit,minmax(280px,1fr));
    gap:20px;
}

.form-group{
    display:flex;
    flex-direction:column;
}

.form-group label{
    margin-bottom:10px;
    font-size:14px;
    font-weight:700;
    color:#475569;
}

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

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

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

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

.users-table{
    width:100%;
    border-collapse:collapse;
}

.users-table th{
    background:#f8fafc;
    padding:16px;
    text-align:left;
    font-size:13px;
    color:#475569;
}

.users-table td{
    padding:16px;
    border-top:1px solid #eef2ff;
    font-size:14px;
    color:#02122c;
}

.edit-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:38px;
    padding:0 16px;
    border-radius:12px;
    background:#dbeafe;
    color:#1d4ed8;
    text-decoration:none;
    font-size:13px;
    font-weight:700;
}

.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:8px 14px;
    border-radius:999px;
    background:#e0e7ff;
    color:#4338ca;
    font-size:12px;
    font-weight:700;
    margin-right:8px;
    margin-bottom:8px;
}

.section-checkbox{
    background:#f8fafc;
    border-radius:18px;
    padding:20px;
    margin-top:20px;
}

.checkbox-grid{
    display:grid;
    grid-template-columns:
    repeat(auto-fit,minmax(240px,1fr));
    gap:14px;
}

.checkbox-item{
    background:#ffffff;
    border-radius:14px;
    padding:14px;
    display:flex;
    align-items:center;
    gap:12px;
}

.role-item{
    display:flex;
    align-items:center;
    justify-content:space-between;
    background:#f8fafc;
    padding:14px 18px;
    border-radius:16px;
    margin-bottom:12px;
}

.delete-role-btn{
    background:#fee2e2;
    color:#991b1b;
    padding:10px 14px;
    border-radius:12px;
    text-decoration:none;
    font-size:13px;
    font-weight:700;
}

</style>

</head>

<body>

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

<div class="content-area">

    <?php if(isset($_GET['msg']) && $_GET['msg'] === 'permissions_moved'): ?>
    <div style="background:#fff3cd;border:1px solid #ffc107;color:#856404;padding:12px 18px;border-radius:8px;margin-bottom:16px;">
        <strong>ℹ️ Aviso:</strong> Los permisos de usuarios ahora se gestionan directamente desde 
        <strong>Editar usuario</strong>. Haz clic en ✏️ junto a cualquier usuario para configurar sus permisos.
    </div>
    <?php endif; ?>

    <div class="top-actions">

        <a
            href="/pages/settings.php"
            class="back-btn"
        >
            ← Volver
        </a>

    </div>

    <div class="page-title">
        Usuarios
    </div>

    <div class="page-subtitle">
        Administración de usuarios del CRM
    </div>

    <div class="white-card">

        <h2
        style="
        margin-bottom:20px;
        color:#02122c;
        "
        >
            Roles visuales
        </h2>

        <form method="POST">

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

            <div
            style="
            display:flex;
            gap:14px;
            flex-wrap:wrap;
            "
            >

                <input
                    type="text"
                    name="role_name"
                    class="form-control"
                    placeholder="Nuevo rol visual"
                    style="max-width:320px;"
                    required
                >

                <button
                    type="submit"
                    class="btn-save"
                    style="
                    margin-top:0;
                    height:54px;
                    "
                >
                    Crear rol
                </button>

            </div>

        </form>

        <div style="margin-top:25px;">

            <?php

            $rolesList = $conn->query("
            SELECT *
            FROM visual_roles
            ORDER BY role_name ASC
            ");

            ?>

            <?php while($role = $rolesList->fetch_assoc()): ?>

                <div class="role-item">

                    <div>

                        <strong>
                            <?= htmlspecialchars($role['role_name']) ?>
                        </strong>

                    </div>

                    <a
                        href="?delete_visual_role=<?= $role['id'] ?>"
                        class="delete-role-btn"
                        onclick="return confirm('¿Eliminar rol visual?')"
                    >
                        Eliminar
                    </a>

                </div>

            <?php endwhile; ?>

        </div>

    </div>

    <div class="white-card">

        <?php if($success): ?>

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

        <?php endif; ?>

        <?php if($error): ?>

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

        <?php endif; ?>

        <form method="POST">

            <div class="form-grid">

                <div class="form-group">

                    <label>
                        Nombre
                    </label>

                    <input
                        type="text"
                        name="name"
                        class="form-control"
                        required
                    >

                </div>

                <div class="form-group">

                    <label>
                        Correo
                    </label>

                    <input
                        type="email"
                        name="email"
                        class="form-control"
                        required
                    >

                </div>

                <div class="form-group">

                    <label>
                        Contraseña
                    </label>

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

                </div>

                <div class="form-group">

                    <label>
                        Cargo visual
                    </label>

                    <select
                        name="visual_role"
                        class="form-control"
                    >

                        <option value="">
                            Seleccionar
                        </option>

                        <?php while($role = $visualRoles->fetch_assoc()): ?>

                            <option value="<?= htmlspecialchars($role['role_name']) ?>">

                                <?= htmlspecialchars($role['role_name']) ?>

                            </option>

                        <?php endwhile; ?>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Líder
                    </label>

                    <select
                        name="leader_id"
                        class="form-control"
                    >

                        <option value="0">
                            Sin líder
                        </option>

                        <?php while($leader = $leaders->fetch_assoc()): ?>

                            <option value="<?= $leader['id'] ?>">
                                <?= $leader['name'] ?>
                            </option>

                        <?php endwhile; ?>

                    </select>

                </div>

            </div>

            <div class="section-checkbox">

                <label
                style="
                display:block;
                margin-bottom:15px;
                font-weight:700;
                "
                >
                    Oficinas asignadas
                </label>

                <div class="checkbox-grid">

                    <?php while($office = $offices->fetch_assoc()): ?>

                        <label class="checkbox-item">

                            <input
                                type="checkbox"
                                name="offices[]"
                                value="<?= $office['id'] ?>"
                            >

                            <?= htmlspecialchars($office['office_name']) ?>

                        </label>

                    <?php endwhile; ?>

                </div>

            </div>

            <div class="section-checkbox">

                <label
                style="
                display:block;
                margin-bottom:15px;
                font-weight:700;
                "
                >
                    Campañas asignadas
                </label>

                <div class="checkbox-grid">

                    <?php while($campaign = $campaigns->fetch_assoc()): ?>

                        <label class="checkbox-item">

                            <input
                                type="checkbox"
                                name="campaigns[]"
                                value="<?= $campaign['id'] ?>"
                            >

                            <?= htmlspecialchars($campaign['campaign_name']) ?>

                        </label>

                    <?php endwhile; ?>

                </div>

            </div>

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

        </form>

    </div>

    <div class="white-card">

        <table class="users-table">

            <thead>

                <tr>

                    <th>ID</th>
                    <th>Nombre</th>
                    <th>Correo</th>
                    <th>Cargo visual</th>
                    <th>Oficinas</th>
                    <th>Campañas</th>
                    <th>Estado</th>
                    <th>Acciones</th>

                </tr>

            </thead>

            <tbody>

                <?php while($user = $users->fetch_assoc()): ?>

                    <?php

                    $user_id =
                    intval($user['id']);

                    $userOffices = $conn->query("
                    SELECT offices.office_name
                    FROM user_offices

                    INNER JOIN offices
                    ON offices.id = user_offices.office_id

                    WHERE user_offices.user_id = '$user_id'
                    ");

                    $userCampaigns = $conn->query("
                    SELECT campaigns.campaign_name
                    FROM user_campaigns

                    INNER JOIN campaigns
                    ON campaigns.id = user_campaigns.campaign_id

                    WHERE user_campaigns.user_id = '$user_id'
                    ");

                    ?>

                    <tr>

                        <td>
                            <?= $user['id'] ?>
                        </td>

                        <td>
                            <?= htmlspecialchars($user['name']) ?>
                        </td>

                        <td>
                            <?= htmlspecialchars($user['email']) ?>
                        </td>

                        <td>

                            <span class="badge">

                                <?= htmlspecialchars($user['visual_role'] ?? '-') ?>

                            </span>

                        </td>

                        <td>

                            <?php while($office = $userOffices->fetch_assoc()): ?>

                                <span class="badge">

                                    <?= htmlspecialchars($office['office_name']) ?>

                                </span>

                            <?php endwhile; ?>

                        </td>

                        <td>

                            <?php while($camp = $userCampaigns->fetch_assoc()): ?>

                                <span class="badge">

                                    <?= htmlspecialchars($camp['campaign_name']) ?>

                                </span>

                            <?php endwhile; ?>

                        </td>

                        <td>

                            <?php if($user['is_active'] == 1): ?>

                                <span
                                style="
                                color:#166534;
                                font-weight:700;
                                "
                                >
                                    Activo
                                </span>

                            <?php else: ?>

                                <span
                                style="
                                color:#991b1b;
                                font-weight:700;
                                "
                                >
                                    Inactivo
                                </span>

                            <?php endif; ?>

                        </td>

                        <td
                        style="
                        display:flex;
                        gap:10px;
                        flex-wrap:wrap;
                        "
                        >

                            <a
                                href="/pages/edit_user.php?id=<?= $user['id'] ?>"
                                class="edit-btn"
                            >
                                Editar
                            </a>

                            <?php if($user['id'] != $_SESSION['user_id']): ?>

                                <a
                                    href="/pages/settings_users.php?toggle_user=<?= $user['id'] ?>"
                                    class="edit-btn"
                                    style="
                                    background:
                                    <?= $user['is_active'] == 1 ? '#fee2e2' : '#dcfce7' ?>;
                                    color:
                                    <?= $user['is_active'] == 1 ? '#991b1b' : '#166534' ?>;
                                    "
                                >
                                    <?= $user['is_active'] == 1 ? 'Desactivar' : 'Activar' ?>
                                </a>

                            <?php endif; ?>

                        </td>

                    </tr>

                <?php endwhile; ?>

            </tbody>

        </table>

    </div>

</div>

</body>
</html>