<?php

session_start();

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

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

/*
|--------------------------------------------------------------------------
| GUARDAR JERARQUÍA
|--------------------------------------------------------------------------
*/

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

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

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

    /*
    |--------------------------------------------------------------------------
    | EVITAR AUTOASIGNACIÓN
    |--------------------------------------------------------------------------
    */

    if($user_id == $leader_id){

        $error =
        "Un usuario no puede ser líder de sí mismo.";

    } else {

        $stmt = $conn->prepare("
        UPDATE users
        SET leader_id = ?
        WHERE id = ?
        ");

        $stmt->bind_param(
            "ii",
            $leader_id,
            $user_id
        );

        $stmt->execute();

        $success =
        "Jerarquía actualizada.";

    }

}

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

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

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

$allUsers = [];

while($row = $users->fetch_assoc()){

    $allUsers[] = $row;

}

?>

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

<head>

<meta charset="UTF-8">

<title>
Jerarquía
</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{
    color:#64748b;
    margin-bottom:30px;
}

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

.user-card{
    background:#f8fafc;
    border-radius:20px;
    padding:24px;
    margin-bottom:20px;
}

.user-name{
    font-size:22px;
    font-weight:800;
    color:#02122c;
}

.user-role{
    color:#64748b;
    margin-top:5px;
    margin-bottom:20px;
}

.form-row{
    display:flex;
    gap:14px;
    flex-wrap:wrap;
    align-items:center;
}

.form-control{
    min-width:280px;
    height:52px;
    border:none;
    background:#ffffff;
    border-radius:16px;
    padding:0 18px;
    font-size:15px;
}

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

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

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

</style>

</head>

<body>

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

<div class="content-area">

    <div class="top-actions">

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

    </div>

    <div class="page-title">
        Jerarquía
    </div>

    <div class="page-subtitle">
        Organigrama y estructura interna 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; ?>

    <?php foreach($allUsers as $user): ?>

        <?php

        $leader_name = "Sin líder";

        if(
            !empty($user['leader_id'])
        ){

            $leaderQuery = $conn->query("
            SELECT name
            FROM users
            WHERE id = '".intval($user['leader_id'])."'
            LIMIT 1
            ");

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

                $leader_name =
                $leaderQuery->fetch_assoc()['name'];

            }

        }

        ?>

        <div class="white-card">

            <div class="user-name">
                <?= htmlspecialchars($user['name']) ?>
            </div>

            <div class="user-role">
                <?= htmlspecialchars($user['visual_role']) ?>
            </div>

            <form method="POST">

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

                <input
                    type="hidden"
                    name="user_id"
                    value="<?= $user['id'] ?>"
                >

                <div class="form-row">

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

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

                        <?php foreach($allUsers as $leader): ?>

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

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

                                    <?= $user['leader_id'] == $leader['id']
                                    ? 'selected'
                                    : '' ?>
                                >

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

                                </option>

                            <?php endif; ?>

                        <?php endforeach; ?>

                    </select>

                    <button
                        type="submit"
                        class="btn-save"
                    >
                        Guardar jerarquía
                    </button>

                </div>

            </form>

        </div>

    <?php endforeach; ?>

</div>

</body>
</html>