<?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);

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

];

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

    die("Usuario no encontrado");

}

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

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

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

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

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

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

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

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

    $permissions = [];

    foreach($columns as $permission){

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

    }

    $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'
            ";

        }

        $sql = "
        UPDATE users
        SET
            name = '".$conn->real_escape_string($name)."',
            email = '".$conn->real_escape_string($email)."',
            office_id = '$office_id',
            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 $cid){

                $cid = intval($cid);

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

            }

        }

        /*
        |--------------------------------------------------------------------------
        | 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.";

    }

}

/*
|--------------------------------------------------------------------------
| CARGAR USUARIO
|--------------------------------------------------------------------------
*/

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

if(!$userResult){

    die($conn->error);

}

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

    die("Usuario no encontrado");

}

$userData = $userResult->fetch_assoc();

if(!$userData || !is_array($userData)){

    die("Error cargando usuario");

}

/*
|--------------------------------------------------------------------------
| 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 = [];

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

if($ucQuery){

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

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

    }

}

?>

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

<head>

<meta charset="UTF-8">

<title>
Editar usuario DEV
</title>

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

<style>

body{
    margin:0;
    background:#f1f5f9;
    overflow-y:auto;
}

.content-area{
    padding:40px;
    min-height:100vh;
}

.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">

    <div class="page-title">
        Editar usuario DEV
    </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="<?php echo htmlspecialchars($userData['name'] ?? ''); ?>"
                        required
                    >

                </div>

                <div class="form-group">

                    <label>Correo</label>

                    <input
                        type="email"
                        name="email"
                        class="form-control"
                        value="<?php echo htmlspecialchars($userData['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'] ?>"
                                    <?= ($userData['office_id'] ?? 0) == $office['id'] ? 'selected' : '' ?>
                                >
                                    <?= htmlspecialchars($office['office_name']) ?>
                                </option>

                            <?php endwhile; ?>

                        <?php endif; ?>

                    </select>

                </div>

                <div class="form-group">

                    <label>Estado</label>

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

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

                        <option
                            value="inactive"
                            <?= ($userData['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"
                            <?= !empty($userData[$permission]) ? '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>