<?php

session_start();

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

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/*
|--------------------------------------------------------------------------
| COLUMNAS EXISTENTES
|--------------------------------------------------------------------------
*/

$columns = [

    '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_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',

    // Telefonia y marcador
    'can_use_marcador',
    'can_view_call_logs',
    'can_manage_telefonia',

    // Leads avanzado
    'can_delete_leads',
    'can_import_leads',

    // Pipeline
    'can_view_pipeline',

    // Logs
    'can_view_logs',

];

/*
|--------------------------------------------------------------------------
| CREAR COLUMNAS NUEVAS SI NO EXISTEN
|--------------------------------------------------------------------------
*/

$new_cols = [
    'can_use_marcador',
    'can_view_call_logs',
    'can_manage_telefonia',
    'can_delete_leads',
    'can_import_leads',
    'can_view_pipeline',
    'can_view_logs',
];

foreach($new_cols as $col){
    $chk = $conn->query("SHOW COLUMNS FROM users LIKE '$col'");
    if($chk && $chk->num_rows == 0){
        $conn->query("ALTER TABLE users ADD COLUMN $col TINYINT(1) DEFAULT 0");
    }
}

/*
|--------------------------------------------------------------------------
| VALIDAR ID
|--------------------------------------------------------------------------
*/

if(!isset($_GET['id'])){

    die("Usuario no encontrado");

}

$edit_user_id = intval($_GET['id']);

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

/*
|--------------------------------------------------------------------------
| OBTENER USUARIO
|--------------------------------------------------------------------------
*/

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

if(!$userQuery){

    die($conn->error);

}

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

    die("Usuario no encontrado");

}

$user = $userQuery->fetch_assoc();
if(!$user || !is_array($user)){ die('Error al cargar el usuario. Verifique que existen las columnas de permisos en la base de datos.'); }

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

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

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

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

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

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

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

    $permissions = [];

    foreach($columns as $permission){

        $permissions[$permission] =
        isset($_POST[$permission]) ? 1 : 0;

    }

    /*
    |--------------------------------------------------------------------------
    | VALIDAR EMAIL
    |--------------------------------------------------------------------------
    */

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

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

        $error =
        "El correo ya está siendo utilizado.";

    } else {

        $password_sql = "";

        if(!empty($_POST['password'])){

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

            $password_sql = ",
            password = '".$conn->real_escape_string($new_password)."'
            ";

        }

        $permissions_sql = "";

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

            $permissions_sql .= ",
            $key = '$value'
            ";

        }

        $leader_id   = intval($_POST['leader_id'] ?? 0);
        $visual_role = $conn->real_escape_string(trim($_POST['visual_role'] ?? 'asesor'));

        $sql = "
        UPDATE users
        SET
            name = '".$conn->real_escape_string($name)."',
            email = '".$conn->real_escape_string($email)."',
            office_id = '$office_id',
            leader_id = '$leader_id',
            visual_role = '$visual_role',
            status = '".$conn->real_escape_string($status)."'
            $permissions_sql
            $password_sql
        WHERE id = '$edit_user_id'
        ";

        $update = $conn->query($sql);

        if(!$update){

            die($conn->error);

        }

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

        $conn->query("
        DELETE FROM user_campaigns
        WHERE user_id = '$edit_user_id'
        ");

        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
                (
                    '$edit_user_id',
                    '$campaign_id'
                )
                ");

            }

        }

        /*
        |--------------------------------------------------------------------------
        | ACTUALIZAR SESSION
        |--------------------------------------------------------------------------
        */

        if(isset($_SESSION['user_id']) && $_SESSION['user_id'] == $edit_user_id){

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

                $_SESSION[$key] = $value;

            }

        }

        $success =
        "Usuario actualizado correctamente.";

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

        $user = $userQuery->fetch_assoc();
if(!$user || !is_array($user)){ die('Error al cargar el usuario. Verifique que existen las columnas de permisos en la base de datos.'); }

    }

}

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

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

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

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

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

$user_campaigns = [];

$userCampaignsQuery = $conn->query("
SELECT campaign_id
FROM user_campaigns
WHERE user_id = '$edit_user_id'
");

if($userCampaignsQuery){

    while($uc = $userCampaignsQuery->fetch_assoc()){

        $user_campaigns[] =
        $uc['campaign_id'];

    }

}

?>

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

<head>

<meta charset="UTF-8">

<title>
Editar usuario
</title>

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

<style>

.content-area{
    width:100%;
    max-width:1400px;
    margin:0 auto;
    padding:40px;
    min-height:100vh;
    overflow-y:auto;
    position:relative;
    z-index:9999;
    background:#f1f5f9;
}

.sidebar{
    display:none !important;
}

body{
    margin:0 !important;
    padding:0 !important;
    background:#f1f5f9;
}

html body .content-area{
    margin-left:0 !important;
    width:100% !important;
}

body{
    overflow-y:auto;
}

.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;
    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:700;
    color:#475569;
}

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

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

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

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

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

.permission-title{
    font-size:22px;
    font-weight:800;
    margin-top:35px;
    margin-bottom:10px;
    color:#02122c;
}

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

</style>

</head>

<body>


<div class="content-area">
    <a
    href="/pages/users.php"
    style="
        display:inline-flex;
        align-items:center;
        gap:10px;
        margin-bottom:25px;
        padding:12px 18px;
        border-radius:14px;
        background:#ffffff;
        text-decoration:none;
        color:#02122c;
        font-weight:700;
        box-shadow:0 10px 25px rgba(15,23,42,.06);
    "
>
    ← Volver
</a>

    <div class="page-title">
        Editar usuario
    </div>

    <div class="page-subtitle">
        Gestión completa de permisos
    </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"
                value="<?= htmlspecialchars($user['name']) ?>"
                required
            >
        </div>

        <div class="form-group">
            <label>Correo</label>

            <input
                type="email"
                name="email"
                class="form-control"
                value="<?= htmlspecialchars($user['email']) ?>"
                required
            >
        </div>

        <div class="form-group">
            <label>Nueva contraseña</label>

            <input
                type="password"
                name="password"
                class="form-control"
                placeholder="Opcional"
            >
        </div>

        <div class="form-group">
            <label>Oficina</label>

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

                <?php if($offices): ?>

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

                        <option
                            value="<?= $office['id'] ?>"
                            <?= $user['office_id'] == $office['id'] ? 'selected' : '' ?>
                        >
                            <?= htmlspecialchars($office['office_name']) ?>
                        </option>

                    <?php endwhile; ?>

                <?php endif; ?>

            </select>
        </div>

        <div class="form-group">
            <label>Supervisor directo (Líder)</label>
            <select name="leader_id" class="form-control">
                <option value="0">Sin supervisor</option>
                <?php
                $all_users = $conn->query("SELECT id, name FROM users WHERE id != '$edit_user_id' ORDER BY name ASC");
                while($u = $all_users->fetch_assoc()):
                ?>
                <option value="<?= $u['id'] ?>" <?= ($user['leader_id'] ?? 0) == $u['id'] ? 'selected' : '' ?>>
                    <?= htmlspecialchars($u['name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
        </div>

        <div class="form-group">
            <label>Rol visual</label>
            <select name="visual_role" class="form-control">
                <option value="asesor" <?= ($user['visual_role'] ?? '') == 'asesor' ? 'selected' : '' ?>>Asesor</option>
                <option value="lider" <?= ($user['visual_role'] ?? '') == 'lider' ? 'selected' : '' ?>>Líder</option>
                <option value="supervisor" <?= ($user['visual_role'] ?? '') == 'supervisor' ? 'selected' : '' ?>>Supervisor</option>
                <option value="admin" <?= ($user['visual_role'] ?? '') == 'admin' ? 'selected' : '' ?>>Admin</option>
            </select>
        </div>

        <div class="form-group">
            <label>Estado</label>

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

                <option
                    value="active"
                    <?= isset($user['status']) && $user['status'] == 'active' ? 'selected' : '' ?>
                >
                    Activo
                </option>

                <option
                    value="inactive"
                    <?= isset($user['status']) && $user['status'] == 'inactive' ? 'selected' : '' ?>
                >
                    Inactivo
                </option>

            </select>
        </div>

    </div>

    <div class="permission-title">
        Permisos del sistema
    </div>

    <div class="permissions-grid">

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

            <label class="permission-box">

                <input
                    type="checkbox"
                    name="<?= $permission ?>"
                    value="1"
                    <?= isset($user[$permission]) && $user[$permission] == 1 ? 'checked' : '' ?>
                >

                <span>
                    <?= ucwords(str_replace("_"," ",str_replace("can_","",$permission))) ?>
                </span>

            </label>

        <?php endforeach; ?>

    </div>

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

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

        <div class="campaign-grid">

            <?php if($campaigns): ?>

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

                    <label class="campaign-box">

                        <input
                            type="checkbox"
                            name="campaigns[]"
                            value="<?= $campaign['id'] ?>"
                            <?= in_array($campaign['id'], $user_campaigns) ? 'checked' : '' ?>
                        >

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

                    </label>

                <?php endwhile; ?>

            <?php endif; ?>

        </div>

    </div>

    <button
        type="submit"
        class="btn-save"
    >
        Guardar cambios
    </button>

</form>
    </div>

</div>

</body>
</html>