<?php

session_start();

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

    header("Location: /login.php");
    exit;

}

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

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

/*
|--------------------------------------------------------------------------
| TABLA USERS
|--------------------------------------------------------------------------
*/

$conn->query("
CREATE TABLE IF NOT EXISTS users (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(150) NOT NULL,

    email VARCHAR(150) NOT NULL UNIQUE,

    password VARCHAR(255) NOT NULL,

    role VARCHAR(50) DEFAULT 'asesor',

    role_id INT NULL,

    office_id INT NULL,

    can_edit_contracts TINYINT(1) DEFAULT 0,

    can_export_contracts TINYINT(1) DEFAULT 0,

    status ENUM('active','inactive') DEFAULT 'active',

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

)
");

/*
|--------------------------------------------------------------------------
| VALIDAR COLUMNAS
|--------------------------------------------------------------------------
*/

$columns = [

    'role_id',
    'can_edit_contracts',
    'can_export_contracts'

];

foreach($columns as $column){

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

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

        if($column == 'role_id'){

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

        } else {

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

        }

    }

}

/*
|--------------------------------------------------------------------------
| TABLA USER CAMPAIGNS
|--------------------------------------------------------------------------
*/

$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

)
");

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

$conn->query("
CREATE TABLE IF NOT EXISTS roles (

    id INT AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(150) NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

)
");

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

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

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

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

    $password =
    password_hash(
        $_POST['password'],
        PASSWORD_DEFAULT
    );

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

    $role_id =
    isset($_POST['role_id'])
    ? intval($_POST['role_id'])
    : 0;

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

    $can_edit_contracts =
    isset($_POST['can_edit_contracts'])
    ? 1
    : 0;

    $can_export_contracts =
    isset($_POST['can_export_contracts'])
    ? 1
    : 0;

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

    if($exists->num_rows > 0){

        $error =
        'El correo ya existe.';

    } else {

        $conn->query("
        INSERT INTO users
        (
            name,
            email,
            password,
            role,
            role_id,
            office_id,
            can_edit_contracts,
            can_export_contracts
        )
        VALUES
        (
            '".$conn->real_escape_string($name)."',
            '".$conn->real_escape_string($email)."',
            '".$password."',
            '".$conn->real_escape_string($role)."',
            '$role_id',
            '$office_id',
            '$can_edit_contracts',
            '$can_export_contracts'
        )
        ");

        $user_id =
        $conn->insert_id;

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

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

            foreach($_POST['campaigns'] as $campaign_id){

                $campaign_id =
                intval($campaign_id);

                $conn->query("
                INSERT INTO user_campaigns
                (
                    user_id,
                    campaign_id
                )
                VALUES
                (
                    '$user_id',
                    '$campaign_id'
                )
                ");

            }

        }

        $success =
        'Usuario creado correctamente.';

    }

}

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

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

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

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

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

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

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

$users = $conn->query("
SELECT
    users.*,
    offices.office_name,
    roles.name AS role_name
FROM users

LEFT JOIN offices
ON offices.id = users.office_id

LEFT JOIN roles
ON roles.id = users.role_id

ORDER BY users.id DESC
");

?>

<!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;
}

.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;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(15,23,42,.06);
}

.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:600;
    color:#5f6b7a;
}

.form-control{
    height:52px;
    border:none;
    background:#f3f5fa;
    border-radius:14px;
    padding:0 16px;
    font-size:15px;
}

select.form-control{
    height:52px;
}

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

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

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

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

.crm-table th{
    text-align:left;
    padding:16px;
    font-size:13px;
    text-transform:uppercase;
    color:#7b8190;
    border-bottom:1px solid #edf0f5;
}

.crm-table td{
    padding:18px 16px;
    border-bottom:1px solid #edf0f5;
    color:#02122c;
    font-size:14px;
}

.role-badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:32px;
    padding:0 14px;
    border-radius:999px;
    background:#eef2ff;
    color:#4338ca;
    font-size:12px;
    font-weight:700;
}

.status-active{
    color:#16a34a;
    font-weight:700;
}

.status-inactive{
    color:#dc2626;
    font-weight:700;
}

.campaign-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
    gap:12px;
    margin-top:10px;
}

.campaign-box{
    display:flex;
    align-items:center;
    gap:10px;
    background:#f3f5fa;
    padding:14px;
    border-radius:14px;
}

.permission-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(250px,1fr));
    gap:12px;
    margin-top:10px;
}

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

</style>

</head>

<body>

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

<div class="content-area">

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

    <div class="page-subtitle">
        Gestión de usuarios, campañas y oficinas
    </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">

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

            <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>
                        Rol visual
                    </label>

                    <select
                        name="role"
                        class="form-control"
                        required
                    >

                        <option value="backoffice">
                            Backoffice
                        </option>

                        <option value="supervisor">
                            Supervisor
                        </option>

                        <option value="lider">
                            Líder
                        </option>

                        <option value="asesor">
                            Asesor
                        </option>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Rol de permisos
                    </label>

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

                        <option value="0">
                            Sin rol
                        </option>

                        <?php while($role_item = $roles->fetch_assoc()): ?>

                            <option value="<?= $role_item['id'] ?>">

                                <?= htmlspecialchars($role_item['name']) ?>

                            </option>

                        <?php endwhile; ?>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Oficina
                    </label>

                    <select
                        name="office_id"
                        class="form-control"
                        required
                    >

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

                            <option value="<?= $office['id'] ?>">

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

                            </option>

                        <?php endwhile; ?>

                    </select>

                </div>

            </div>

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

                <label
                    style="
                    display:block;
                    margin-bottom:14px;
                    font-size:14px;
                    font-weight:600;
                    color:#5f6b7a;
                    "
                >
                    Permisos rápidos
                </label>

                <div class="permission-grid">

                    <label class="permission-box">

                        <input
                            type="checkbox"
                            name="can_edit_contracts"
                            value="1"
                        >

                        <span>
                            Puede editar contratos
                        </span>

                    </label>

                    <label class="permission-box">

                        <input
                            type="checkbox"
                            name="can_export_contracts"
                            value="1"
                        >

                        <span>
                            Puede exportar contratos
                        </span>

                    </label>

                </div>

            </div>

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

                <label
                    style="
                    display:block;
                    margin-bottom:14px;
                    font-size:14px;
                    font-weight:600;
                    color:#5f6b7a;
                    "
                >
                    Campañas
                </label>

                <div class="campaign-grid">

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

                        <label class="campaign-box">

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

                            <span>
                                <?= htmlspecialchars($campaign['name']) ?>
                            </span>

                        </label>

                    <?php endwhile; ?>

                </div>

            </div>

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

        </form>

    </div>

    <div class="white-card">

        <div class="page-subtitle">
            Usuarios registrados
        </div>

        <table class="crm-table">

            <thead>

                <tr>

                    <th>ID</th>
                    <th>Nombre</th>
                    <th>Correo</th>
                    <th>Rol</th>
                    <th>Permisos</th>
                    <th>Oficina</th>
                    <th>Estado</th>
                    <th>Acciones</th>

                </tr>

            </thead>

            <tbody>

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

                    <tr>

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

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

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

                        <td>

                            <span class="role-badge">

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

                            </span>

                        </td>

                        <td>

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

                                <div>
                                    Editar contratos
                                </div>

                            <?php endif; ?>

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

                                <div>
                                    Exportar contratos
                                </div>

                            <?php endif; ?>

                            <?php if(
                                $user['can_edit_contracts'] == 0
                                &&
                                $user['can_export_contracts'] == 0
                            ): ?>

                                -

                            <?php endif; ?>

                        </td>

                        <td>

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

                        </td>

                        <td>

    <?php

    $status =
    isset($user['status'])
    ? $user['status']
    : 'active';

    ?>

    <span class="<?= $status == 'active' ? 'status-active' : 'status-inactive' ?>">

        <?= htmlspecialchars($status) ?>

    </span>

</td>

<td>

    <a
        href="/pages/edit_user.php?id=<?= $user['id'] ?>"
        style="
        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;
        "
    >
        Editar
    </a>

</td>

</tr>

                <?php endwhile; ?>

            </tbody>

        </table>

    </div>

</div>

</body>
</html>