<?php
require __DIR__ . '/../helpers/auth.php';
auth_check();
$user = auth_user();
?>
<?php
$menu  = 'profile';
$title = 'Profil Akun';

session_start();
require __DIR__ . '/../api/monitoring/koneksi.php';

// ======================
// AUTH CHECK
// ======================
if (empty($_SESSION['user'])) {
    header("Location: /monitoring/login.php");
    exit;
}

$user_id = (int)$_SESSION['user']['id'];

// ======================
// Ambil data user terbaru
// ======================
$stmt = $conn->prepare("SELECT id, name, email, password FROM users WHERE id=? LIMIT 1");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

$success = '';
$error   = '';

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

    $name         = trim($_POST['name']);
    $old_password = $_POST['old_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_pass = $_POST['confirm_password'] ?? '';

    // ===== Update Nama =====
    if (!empty($name) && $name !== $user['name']) {
        $stmt = $conn->prepare("UPDATE users SET name=? WHERE id=?");
        $stmt->bind_param("si", $name, $user_id);
        $stmt->execute();

        $_SESSION['user']['name'] = $name;
        $success = "Profil berhasil diperbarui.";
    }

    // ===== Update Password =====
    if (!empty($new_password)) {

        if (empty($old_password)) {
            $error = "Password lama wajib diisi.";
        } elseif (!password_verify($old_password, $user['password'])) {
            $error = "Password lama salah.";
        } elseif (strlen($new_password) < 6) {
            $error = "Password baru minimal 6 karakter.";
        } elseif ($new_password !== $confirm_pass) {
            $error = "Konfirmasi password tidak cocok.";
        } else {

            $hash = password_hash($new_password, PASSWORD_BCRYPT);

            $stmt = $conn->prepare("UPDATE users SET password=? WHERE id=?");
            $stmt->bind_param("si", $hash, $user_id);
            $stmt->execute();

            $success = "Password berhasil diganti.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title><?= $title ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/dashboard.css">

<style>
.profile-form {
    max-width: 480px;
    background: #fff;
    padding: 22px;
    border-radius: 10px;
    box-shadow: 0 2px 6px rgba(0,0,0,.08);
}
.profile-form label {
    display: block;
    margin: 14px 0;
    font-weight: 500;
}
.profile-form input {
    width: 100%;
    padding: 8px;
    margin-top: 6px;
}
.profile-form button {
    margin-top: 18px;
    padding: 10px 18px;
    background: #2b7cff;
    border: none;
    color: #fff;
    border-radius: 6px;
    cursor: pointer;
}
.profile-form button:hover {
    opacity: .9;
}
.alert-success { color: green; }
.alert-error   { color: red; }
small { color:#666; }
</style>
</head>

<body>
<div class="app">

    <?php include __DIR__ . '/../layout/sidebar.php'; ?>

    <main class="main">
        <?php include __DIR__ . '/../layout/header.php'; ?>

        <h2><?= $title ?></h2>

        <?php if ($success): ?>
            <p class="alert-success"><?= $success ?></p>
        <?php endif; ?>

        <?php if ($error): ?>
            <p class="alert-error"><?= $error ?></p>
        <?php endif; ?>

        <form method="POST" class="profile-form">

            <label>
                👤 Nama
                <input type="text" name="name"
                       value="<?= htmlspecialchars($user['name']) ?>" required>
            </label>

            <label>
                📧 Email (tidak bisa diubah)
                <input type="email"
                       value="<?= htmlspecialchars($user['email']) ?>" disabled>
            </label>

            <hr>

            <label>
                🔑 Password Lama
                <input type="password" name="old_password">
            </label>

            <label>
                🔐 Password Baru
                <input type="password" name="new_password">
                <small>Kosongkan jika tidak ingin mengganti password</small>
            </label>

            <label>
                🔐 Konfirmasi Password Baru
                <input type="password" name="confirm_password">
            </label>

            <button type="submit">💾 Simpan Perubahan</button>

        </form>

    </main>
</div>
</body>
</html>
