<?php
session_start();

// 1. VERIFICACIÓN DE SESIÓN Y CARGA DE DEPENDENCIAS
if (!isset($_SESSION['userid'])) {
    header("Location: ../../login/");
    exit();
}
require_once '../../config.php';
require_once '../../vendor/autoload.php'; // COMPOSER

// 2. INICIALIZACIÓN DE VARIABLES DE PÁGINA
$userid = $_SESSION['userid'];
$page = 'perfil'; // Identificador para el menú activo
$alerts_html = '';

// 3. LÓGICA DE PROCESAMIENTO DE FORMULARIOS (POST REQUESTS)

// Lógica para subir foto de perfil
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['profilePicture'])) {
    $file = $_FILES['profilePicture'];
    $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif'];
    $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    if (in_array($fileExtension, $allowedExtensions)) {
        $image = null;
        switch ($fileExtension) {
            case 'png': $image = imagecreatefrompng($file['tmp_name']); break;
            case 'jpg': case 'jpeg': $image = imagecreatefromjpeg($file['tmp_name']); break;
            case 'gif': $image = imagecreatefromgif($file['tmp_name']); break;
        }

        if ($image !== null) {
            $targetDir = '../../assets/img/profiles/';
            $targetFile = $targetDir . $userid . '.png';
            if (file_exists($targetFile)) { unlink($targetFile); }

            if (imagepng($image, $targetFile)) {
                $alerts_html .= '<div class="alert alert-success" role="alert">' . htmlspecialchars($translations["success-update"]) . '</div>';
            } else {
                $alerts_html .= '<div class="alert alert-danger" role="alert">' . htmlspecialchars($translations["unexpected-error"]) . '</div>';
            }
            imagedestroy($image);
        }
    } else {
        $alerts_html .= '<div class="alert alert-danger">' . htmlspecialchars($translations["onlypng"]) . '</div>';
    }
}

// Lógica para cambiar contraseña
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['currentPassword'], $_POST['newPassword'], $_POST['confirmPassword'])) {
    $currentPassword = $_POST['currentPassword'];
    $newPassword = $_POST['newPassword'];
    $confirmPassword = $_POST['confirmPassword'];

    if ($newPassword !== $confirmPassword) {
        $alerts_html .= '<div class="alert alert-warning" role="alert">' . htmlspecialchars($translations["twopasswordnot"]) . '</div>';
    } else {
        $sql_pass = "SELECT password FROM users WHERE userid = ?";
        $stmt_pass = $conn->prepare($sql_pass);
        $stmt_pass->bind_param("i", $userid);
        $stmt_pass->execute();
        $stmt_pass->bind_result($hashedPassword);
        $stmt_pass->fetch();
        $stmt_pass->close();

        if (!password_verify($currentPassword, $hashedPassword)) {
            $alerts_html .= '<div class="alert alert-danger" role="alert">' . htmlspecialchars($translations["error-old-password"]) . '</div>';
        } else {
            $newHashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
            $updateSql = "UPDATE users SET password = ? WHERE userid = ?";
            $updateStmt = $conn->prepare($updateSql);
            $updateStmt->bind_param("si", $newHashedPassword, $userid);
            if ($updateStmt->execute()) {
                $alerts_html .= '<div class="alert alert-success" role="alert">' . htmlspecialchars($translations["success-new-password"]) . '</div>';
                // Aquí iría la lógica de envío de email de notificación
            } else {
                $alerts_html .= '<div class="alert alert-danger" role="alert">' . htmlspecialchars($translations["unexpected-error"]) . '</div>';
            }
            $updateStmt->close();
        }
    }
}

// Lógica para eliminar usuario
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_user'])) {
    $sql_delete = "DELETE FROM users WHERE userid = ?";
    $stmt_delete = $conn->prepare($sql_delete);
    $stmt_delete->bind_param("i", $userid);
    if ($stmt_delete->execute()) {
        session_unset();
        session_destroy();
        header("Location: ../../");
        exit();
    } else {
        $alerts_html .= '<div class="alert alert-danger" role="alert">' . htmlspecialchars($translations["unexpected-error"]) . ": " . $stmt_delete->error . '</div>';
    }
    $stmt_delete->close();
}

// 4. OBTENER DATOS PARA MOSTRAR EN LA PÁGINA
$sql_user = "SELECT firstname, lastname, email FROM users WHERE userid = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $userid);
$stmt_user->execute();
$stmt_user->bind_result($lastname, $firstname, $mail);
$stmt_user->fetch();
$stmt_user->close();

// 5. INCLUIR LA CABECERA DEL DASHBOARD
require_once '../../assets/templates/header-dashboard.php';
?>

<!-- INICIO DEL CONTENIDO ESPEĆIFICO DE LA PÁGINA -->
<div class="d-none topnav d-sm-inline-block">
    <h4><?php echo htmlspecialchars($translations["welcome"]); ?> <?php echo htmlspecialchars($lastname); ?> <?php echo htmlspecialchars($firstname); ?></h4>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#logoutModal">
        <?php echo htmlspecialchars($translations["logout"]); ?>
    </button>
</div>

<?php echo $alerts_html; ?>

<div class="row">
    <div class="col-sm-4">
        <div class="card">
            <div class="card-body">
                <form id="uploadForm" action="" method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-9">
                            <div class="form-group">
                                <label for="profilePicture" class="form-label"><?php echo htmlspecialchars($translations["select-upload-profile"]); ?></label>
                                <input type="file" class="form-control" id="profilePicture" name="profilePicture" accept=".png,.jpg,.jpeg,.gif" required>
                                <div id="fileHelp" class="form-text"><small><?php echo htmlspecialchars($translations["onlypng"]); ?></small></div>
                            </div>
                        </div>
                        <?php
                        $profilePicPath = '/gymprueba/assets/img/profiles/' . $userid . '.png';
                        $profilePicSystemPath = __DIR__ . '../../assets/img/profiles/' . $userid . '.png';
                        if (file_exists($profilePicSystemPath)): ?>
                            <div class="col-md-3 text-center">
                                <img src="<?php echo $profilePicPath; ?>?t=<?php echo time(); ?>" alt="User" class="img-rounded img-fluid mb-3" height="150">
                            </div>
                        <?php endif; ?>
                    </div>
                    <button type="submit" class="btn btn-primary"><?php echo htmlspecialchars($translations["upload"]); ?></button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="card">
            <div class="card-body">
                <form id="passwordChangeForm" method="POST" action="">
                    <div class="form-group">
                        <label for="currentPassword" class="form-label"><?php echo htmlspecialchars($translations["curpassword"]); ?></label>
                        <input type="password" class="form-control" id="currentPassword" name="currentPassword" required>
                    </div>
                    <div class="form-group">
                        <label for="newPassword" class="form-label"><?php echo htmlspecialchars($translations["newpassword"]); ?></label>
                        <input type="password" class="form-control" id="newPassword" name="newPassword" required>
                    </div>
                    <div class="form-group">
                        <label for="confirmPassword" class="form-label"><?php echo htmlspecialchars($translations["password-confirm"]); ?>:</label>
                        <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" required>
                    </div>
                    <button type="submit" class="btn btn-primary"><?php echo htmlspecialchars($translations["save"]); ?></button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-sm-4">
        <div class="card">
            <div class="card-body">
                <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#DeleteModal">
                    <i class="bi bi-x-lg"></i> <?php echo htmlspecialchars($translations["deleteuser"]); ?>
                </button>
            </div>
        </div>
    </div>
</div>

<!-- MODAL DE ELIMINACIÓN DE CUENTA (Específico de esta página) -->
<div class="modal fade" id="DeleteModal" tabindex="-1" role="dialog" aria-labelledby="DeleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="POST" action="">
                <div class="modal-header">
                    <h5 class="modal-title lead" id="deleteAccountModalLabel"><?php echo htmlspecialchars($translations["deleteuser"]); ?></h5>
                </div>
                <div class="modal-body">
                    <p><?php echo htmlspecialchars($translations["areyousuredelete"]); ?></p>
                    <pre tabindex="0"><ul>
                        <li><?php echo htmlspecialchars($translations["deletemodalfirst"]); ?></li>
                        <li><?php echo htmlspecialchars($translations["deletemodalsecond"]); ?></li>
                        <li><?php echo htmlspecialchars($translations["deletemodalthree"]); ?></li>
                        <li><?php echo htmlspecialchars($translations["deletemodalfour"]); ?></li>
                        <li><?php echo htmlspecialchars($translations["deletemodalfive"]); ?></li>
                    </ul></pre>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php echo htmlspecialchars($translations["not-yet"]); ?></button>
                    <button type="submit" name="delete_user" class="btn btn-danger"><?php echo htmlspecialchars($translations["delete"]); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- FIN DEL CONTENIDO ESPEĆIFICO DE LA PÁGINA -->

<?php
// 6. INCLUIR EL PIE DE PÁGINA DEL DASHBOARD
require_once '../../assets/templates/footer-dashboard.php';
?>