<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

require_once __DIR__ . '/../config/database.php';
if (file_exists(__DIR__ . '/../config/app.php')) {
    require_once __DIR__ . '/../config/app.php';
}
require_once __DIR__ . '/../config/master_auth.php';
if (file_exists(__DIR__ . '/../includes/functions.php')) {
    require_once __DIR__ . '/../includes/functions.php';
}

if (function_exists('checkAuth')) {
    checkAuth();
} elseif (function_exists('require_login')) {
    require_login();
}

if (!function_exists('e')) {
    function e($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('up_table_columns')) {
    function up_table_columns(mysqli $conn, string $table): array
    {
        $cols = [];
        $safe = preg_replace('/[^A-Za-z0-9_]/', '', $table);
        $res = $conn->query("SHOW COLUMNS FROM `$safe`");
        if ($res) {
            while ($row = $res->fetch_assoc()) {
                $cols[strtolower((string)$row['Field'])] = (string)$row['Field'];
            }
        }
        return $cols;
    }
}

if (!function_exists('up_column_exists')) {
    function up_column_exists(mysqli $conn, string $table, string $column): bool
    {
        $cols = up_table_columns($conn, $table);
        return isset($cols[strtolower($column)]);
    }
}

if (!function_exists('up_unit_code_from_name')) {
    function up_unit_code_from_name(string $name): string
    {
        $code = strtoupper(trim($name));
        $code = preg_replace('/[^A-Z0-9]+/', '', $code);
        return substr($code !== '' ? $code : ('UNIT' . date('YmdHis')), 0, 50);
    }
}

if (!function_exists('up_seed_nursing_units')) {
    function up_seed_nursing_units(mysqli $conn): void
    {
        $units = [
            ['IGD', 'IGD'],
            ['VK', 'VK / Kamar Bersalin'],
            ['OK', 'OK / Kamar Operasi'],
            ['POLIKLINIK', 'Poliklinik'],
            ['HD', 'HD / Hemodialisa'],
            ['PAVCANIGARA', 'Pav. Canigara'],
            ['PAVCEMPAKA', 'Pav. Cempaka'],
            ['PAVCENDANA', 'Pav. Cendana'],
            ['CEMPAKAUTARA', 'Cempaka Utara'],
            ['RUANGBAYI', 'Ruang Bayi'],
            ['NICU', 'NICU'],
            ['ICU', 'ICU'],
        ];

        $cols = up_table_columns($conn, 'units');
        $hasCode = isset($cols['code']);
        $hasActive = isset($cols['is_active']);

        foreach ($units as [$code, $name]) {
            $existingId = 0;

            if ($hasCode) {
                $stmt = $conn->prepare("SELECT id FROM units WHERE code = ? LIMIT 1");
                if ($stmt) {
                    $stmt->bind_param('s', $code);
                    $stmt->execute();
                    $res = $stmt->get_result();
                    if ($row = $res->fetch_assoc()) $existingId = (int)$row['id'];
                    $stmt->close();
                }
            }

            if ($existingId <= 0) {
                $stmt = $conn->prepare("SELECT id FROM units WHERE name = ? LIMIT 1");
                if ($stmt) {
                    $stmt->bind_param('s', $name);
                    $stmt->execute();
                    $res = $stmt->get_result();
                    if ($row = $res->fetch_assoc()) $existingId = (int)$row['id'];
                    $stmt->close();
                }
            }

            if ($existingId > 0) {
                if ($hasCode && $hasActive) {
                    $stmt = $conn->prepare("UPDATE units SET code = ?, name = ?, is_active = 1 WHERE id = ?");
                    $stmt->bind_param('ssi', $code, $name, $existingId);
                } elseif ($hasCode) {
                    $stmt = $conn->prepare("UPDATE units SET code = ?, name = ? WHERE id = ?");
                    $stmt->bind_param('ssi', $code, $name, $existingId);
                } elseif ($hasActive) {
                    $stmt = $conn->prepare("UPDATE units SET name = ?, is_active = 1 WHERE id = ?");
                    $stmt->bind_param('si', $name, $existingId);
                } else {
                    $stmt = $conn->prepare("UPDATE units SET name = ? WHERE id = ?");
                    $stmt->bind_param('si', $name, $existingId);
                }
                if ($stmt) { $stmt->execute(); $stmt->close(); }
                continue;
            }

            try {
                if ($hasCode && $hasActive) {
                    $stmt = $conn->prepare("INSERT INTO units (code, name, is_active) VALUES (?, ?, 1) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id), name = VALUES(name), is_active = 1");
                    $stmt->bind_param('ss', $code, $name);
                } elseif ($hasCode) {
                    $stmt = $conn->prepare("INSERT INTO units (code, name) VALUES (?, ?) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id), name = VALUES(name)");
                    $stmt->bind_param('ss', $code, $name);
                } elseif ($hasActive) {
                    $stmt = $conn->prepare("INSERT INTO units (name, is_active) VALUES (?, 1) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id), is_active = 1");
                    $stmt->bind_param('s', $name);
                } else {
                    $stmt = $conn->prepare("INSERT INTO units (name) VALUES (?)");
                    $stmt->bind_param('s', $name);
                }
                if ($stmt) { $stmt->execute(); $stmt->close(); }
            } catch (Throwable $e) {
                error_log('Seed unit gagal ' . $name . ': ' . $e->getMessage());
            }
        }
    }
}

if (!function_exists('up_get_valid_unit_id')) {
    function up_get_valid_unit_id(mysqli $conn, $candidate, ?int $fallback = null): ?int
    {
        $id = (int)$candidate;
        if ($id > 0) {
            $stmt = $conn->prepare("SELECT id FROM units WHERE id = ? LIMIT 1");
            if ($stmt) {
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $res = $stmt->get_result();
                $exists = (bool)$res->fetch_assoc();
                $stmt->close();
                if ($exists) return $id;
            }
        }
        if ($fallback && $fallback > 0) {
            $stmt = $conn->prepare("SELECT id FROM units WHERE id = ? LIMIT 1");
            if ($stmt) {
                $stmt->bind_param('i', $fallback);
                $stmt->execute();
                $res = $stmt->get_result();
                $exists = (bool)$res->fetch_assoc();
                $stmt->close();
                if ($exists) return (int)$fallback;
            }
        }
        return null;
    }
}

if (!function_exists('up_get_user_password_hash')) {
    function up_get_user_password_hash(array $userRow): string
    {
        foreach (['password_hash', 'password', 'user_password'] as $col) {
            if (array_key_exists($col, $userRow) && (string)$userRow[$col] !== '') {
                return (string)$userRow[$col];
            }
        }
        return '';
    }
}

if (!function_exists('up_password_matches')) {
    function up_password_matches(string $input, string $stored): bool
    {
        if ($stored === '') return false;
        if (password_get_info($stored)['algo'] !== 0) {
            return password_verify($input, $stored);
        }
        return hash_equals($stored, $input);
    }
}

$conn = getConnection();
if (!$conn instanceof mysqli) {
    echo "<div class='p-6 text-red-700'>Koneksi database gagal.</div>";
    return;
}

try {
    up_seed_nursing_units($conn);
} catch (Throwable $e) {
    error_log('Seed unit profile gagal: ' . $e->getMessage());
}

$masterUser = function_exists('current_user') ? current_user() : ($_SESSION['user'] ?? null);
if (!$masterUser || empty($masterUser['employee_id'])) {
    echo "<div class='p-6'>User tidak teridentifikasi. Silakan login ulang.</div>";
    return;
}

$employee_id = (int)$masterUser['employee_id'];
$message = '';
$error = '';

$employeeCols = up_table_columns($conn, 'employees');
$userCols = up_table_columns($conn, 'users');

if (!isset($employeeCols['join_date'])) {
    try { $conn->query("ALTER TABLE employees ADD COLUMN join_date DATE NULL AFTER position_name"); } catch (Throwable $e) {}
}
if (!isset($userCols['action_passcode_hash'])) {
    try { $conn->query("ALTER TABLE users ADD COLUMN action_passcode_hash VARCHAR(255) NULL AFTER password_hash"); } catch (Throwable $e) {
        try { $conn->query("ALTER TABLE users ADD COLUMN action_passcode_hash VARCHAR(255) NULL"); } catch (Throwable $e2) {}
    }
}

$employeeCols = up_table_columns($conn, 'employees');
$userCols = up_table_columns($conn, 'users');

$sql = "
    SELECT 
        u.id AS user_id,
        u.username,
        u.role,
        u.access_scope,
        u.action_passcode_hash,
        " . (isset($userCols['password_hash']) ? "u.password_hash," : "NULL AS password_hash,") . "
        " . (isset($userCols['password']) ? "u.password," : "NULL AS password,") . "
        " . (isset($userCols['user_password']) ? "u.user_password," : "NULL AS user_password,") . "
        e.id AS employee_id,
        e.nik,
        e.full_name,
        e.phone,
        e.email,
        e.photo_path,
        e.profession,
        e.position_name,
        e.join_date,
        e.unit_id,
        un.name AS unit_name
    FROM employees e
    LEFT JOIN users u ON u.employee_id = e.id
    LEFT JOIN units un ON e.unit_id = un.id
    WHERE e.id = ?
    LIMIT 1
";
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $employee_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$user) {
    echo "<div class='p-6'>Data profil tidak ditemukan. Silakan hubungi administrator.</div>";
    return;
}

// Isi default passcode jika belum ada.
if (!empty($user['user_id']) && empty($user['action_passcode_hash']) && up_column_exists($conn, 'users', 'action_passcode_hash')) {
    $defaultPasscodeHash = password_hash('1234', PASSWORD_DEFAULT);
    $stmt = $conn->prepare("UPDATE users SET action_passcode_hash = ? WHERE id = ?");
    if ($stmt) {
        $uid = (int)$user['user_id'];
        $stmt->bind_param('si', $defaultPasscodeHash, $uid);
        $stmt->execute();
        $stmt->close();
        $user['action_passcode_hash'] = $defaultPasscodeHash;
    }
}

$unitOptions = [];
$unitSql = "SELECT id, name FROM units WHERE 1=1";
if (up_column_exists($conn, 'units', 'is_active')) {
    $unitSql .= " AND is_active = 1";
}
$unitSql .= " ORDER BY FIELD(name, 'IGD','VK / Kamar Bersalin','OK / Kamar Operasi','Poliklinik','HD / Hemodialisa','Pav. Canigara','Pav. Cempaka','Pav. Cendana','Cempaka Utara','Ruang Bayi','NICU','ICU'), name ASC";
$resUnits = $conn->query($unitSql);
if ($resUnits) {
    while ($r = $resUnits->fetch_assoc()) {
        $unitOptions[] = $r;
    }
}

$position_options = [
    'Staf Pelaksana (PA)' => 'Staf Pelaksana (PA)',
    'Perawat Primer (PP)' => 'Perawat Primer (PP)',
    'Katim' => 'Katim',
    'Ka.Unit' => 'Ka.Unit',
    'Kasubdiv Keperawatan Rawat Jalan' => 'Kasubdiv Keperawatan Rawat Jalan',
    'Kasubdiv Keperawatan Rawat Inap' => 'Kasubdiv Keperawatan Rawat Inap',
    'Kepala Divisi Keperawatan' => 'Kepala Divisi Keperawatan',
];
$profession_options = [
    'perawat' => 'Perawat',
    'bidan' => 'Bidan',
    'admin' => 'Admin',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_profile') {
        $full_name = trim($_POST['full_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $position_name = trim($_POST['position_name'] ?? '');
        $profession = trim($_POST['profession'] ?? '');
        $join_date = trim($_POST['join_date'] ?? '');
        $oldUnitId = !empty($user['unit_id']) ? (int)$user['unit_id'] : null;
        $unit_id = up_get_valid_unit_id($conn, $_POST['unit_id'] ?? 0, $oldUnitId);

        $join_date_db = null;
        if ($join_date !== '') {
            $tsJoin = strtotime($join_date);
            if ($tsJoin === false) {
                $error = 'Tanggal bergabung tidak valid.';
            } else {
                $join_date_db = date('Y-m-d', $tsJoin);
            }
        }

        if ($full_name === '') {
            $error = 'Nama lengkap tidak boleh kosong.';
        }

        $photo_path = (string)($user['photo_path'] ?? '');
        if (!$error && isset($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            $allowed = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
            if (!in_array($ext, $allowed, true)) {
                $error = 'Format foto tidak didukung. Gunakan JPG, PNG, WEBP, atau GIF.';
            } else {
                $upload_dir = __DIR__ . '/../uploads/profiles/';
                if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
                $new_filename = 'profile_' . (int)$user['employee_id'] . '_' . time() . '.' . $ext;
                $dest = $upload_dir . $new_filename;
                if (move_uploaded_file($_FILES['photo']['tmp_name'], $dest)) {
                    if (!empty($photo_path) && file_exists(__DIR__ . '/../' . $photo_path)) {
                        @unlink(__DIR__ . '/../' . $photo_path);
                    }
                    $photo_path = 'uploads/profiles/' . $new_filename;
                } else {
                    $error = 'Gagal upload foto.';
                }
            }
        }

        if (!$error) {
            $stmt = $conn->prepare("UPDATE employees SET full_name = ?, email = ?, phone = ?, photo_path = ?, unit_id = ?, position_name = ?, profession = ?, join_date = ? WHERE id = ?");
            if (!$stmt) {
                $error = 'Prepare update profil gagal: ' . $conn->error;
            } else {
                if ($unit_id === null) {
                    $nullUnit = null;
                    $stmt->bind_param('ssssisssi', $full_name, $email, $phone, $photo_path, $nullUnit, $position_name, $profession, $join_date_db, $employee_id);
                } else {
                    $unitInt = (int)$unit_id;
                    $stmt->bind_param('ssssisssi', $full_name, $email, $phone, $photo_path, $unitInt, $position_name, $profession, $join_date_db, $employee_id);
                }
                if ($stmt->execute()) {
                    $_SESSION['full_name'] = $full_name;
                    $_SESSION['user']['full_name'] = $full_name;
                    echo '<script>window.location.href="?module=user_profile&success=1";</script>';
                    exit;
                }
                $error = 'Gagal update profil: ' . $stmt->error;
                $stmt->close();
            }
        }
    }

    if ($action === 'change_password') {
        $old = (string)($_POST['old_password'] ?? '');
        $new = (string)($_POST['new_password'] ?? '');
        $confirm = (string)($_POST['confirm_password'] ?? '');
        $stored = up_get_user_password_hash($user);

        if ($old === '' || $new === '' || $confirm === '') {
            $error = 'Semua field password wajib diisi.';
        } elseif (!up_password_matches($old, $stored)) {
            $error = 'Password lama tidak sesuai.';
        } elseif (strlen($new) < 6) {
            $error = 'Password baru minimal 6 karakter.';
        } elseif ($new !== $confirm) {
            $error = 'Konfirmasi password baru tidak sama.';
        } elseif (empty($user['user_id'])) {
            $error = 'Akun user tidak ditemukan.';
        } else {
            $hash = password_hash($new, PASSWORD_DEFAULT);
            $passwordCol = isset($userCols['password_hash']) ? 'password_hash' : (isset($userCols['password']) ? 'password' : (isset($userCols['user_password']) ? 'user_password' : ''));
            if ($passwordCol === '') {
                $error = 'Kolom password user tidak ditemukan.';
            } else {
                $stmt = $conn->prepare("UPDATE users SET `$passwordCol` = ? WHERE id = ?");
                $uid = (int)$user['user_id'];
                $stmt->bind_param('si', $hash, $uid);
                if ($stmt->execute()) {
                    echo '<script>window.location.href="?module=user_profile&password_success=1";</script>';
                    exit;
                }
                $error = 'Gagal mengganti password: ' . $stmt->error;
                $stmt->close();
            }
        }
    }

    if ($action === 'change_passcode') {
        $old = (string)($_POST['old_passcode'] ?? '');
        $new = (string)($_POST['new_passcode'] ?? '');
        $confirm = (string)($_POST['confirm_passcode'] ?? '');
        $storedPasscode = (string)($user['action_passcode_hash'] ?? '');

        if (empty($user['user_id'])) {
            $error = 'Akun user tidak ditemukan.';
        } elseif ($old === '' || $new === '' || $confirm === '') {
            $error = 'Semua field passcode wajib diisi.';
        } elseif ($storedPasscode !== '' && !password_verify($old, $storedPasscode)) {
            $error = 'Passcode lama tidak sesuai.';
        } elseif (!preg_match('/^[0-9]{4,8}$/', $new)) {
            $error = 'Passcode baru harus angka 4 sampai 8 digit.';
        } elseif ($new !== $confirm) {
            $error = 'Konfirmasi passcode baru tidak sama.';
        } else {
            $hash = password_hash($new, PASSWORD_DEFAULT);
            $stmt = $conn->prepare("UPDATE users SET action_passcode_hash = ? WHERE id = ?");
            $uid = (int)$user['user_id'];
            $stmt->bind_param('si', $hash, $uid);
            if ($stmt->execute()) {
                echo '<script>window.location.href="?module=user_profile&passcode_success=1";</script>';
                exit;
            }
            $error = 'Gagal mengganti passcode: ' . $stmt->error;
            $stmt->close();
        }
    }
}

if (isset($_GET['success'])) $message = 'Profil berhasil diperbarui.';
if (isset($_GET['password_success'])) $message = 'Password berhasil diganti.';
if (isset($_GET['passcode_success'])) $message = 'Passcode berhasil diganti.';

// Refresh data terbaru
$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $employee_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc() ?: $user;
$stmt->close();
?>
<div class="max-w-5xl mx-auto p-4 md:p-6 space-y-6">
    <div class="flex justify-between items-center">
        <h1 class="text-2xl font-bold text-gray-800">Profil Saya</h1>
        <a href="?module=dashboard" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300">
            <i class="fas fa-arrow-left mr-2"></i> Kembali ke Dashboard
        </a>
    </div>

    <?php if ($message): ?>
        <div class="bg-green-100 border-l-4 border-green-500 text-green-700 p-4 rounded"><?= e($message) ?></div>
    <?php endif; ?>
    <?php if ($error): ?>
        <div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded"><?= e($error) ?></div>
    <?php endif; ?>

    <div class="bg-white rounded-2xl shadow-md overflow-hidden">
        <div class="bg-gradient-to-r from-blue-600 to-indigo-600 px-6 py-4">
            <h2 class="text-xl font-semibold text-white flex items-center"><i class="fas fa-user-circle mr-2"></i> Edit Profil</h2>
        </div>
        <div class="p-6">
            <form method="POST" enctype="multipart/form-data" id="profileForm" class="flex flex-col md:flex-row gap-6">
                <input type="hidden" name="action" value="update_profile">
                <div class="flex flex-col items-center space-y-3">
                    <div class="w-32 h-32 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden border-4 border-blue-500">
                        <?php if (!empty($user['photo_path']) && file_exists(__DIR__ . '/../' . $user['photo_path'])): ?>
                            <img src="<?= e($user['photo_path']) ?>" class="w-full h-full object-cover" alt="Foto">
                        <?php else: ?>
                            <i class="fas fa-user-circle text-6xl text-gray-400"></i>
                        <?php endif; ?>
                    </div>
                    <label class="text-sm bg-gray-100 px-3 py-1 rounded-full hover:bg-gray-200 cursor-pointer">
                        <i class="fas fa-camera"></i> Ganti Foto
                        <input type="file" name="photo" accept="image/*" class="hidden">
                    </label>
                </div>

                <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">Nama Lengkap dengan Gelar</label>
                        <input type="text" name="full_name" value="<?= e($user['full_name'] ?? '') ?>" class="w-full px-4 py-2 border rounded-lg" required>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">NIK / ID Karyawan</label>
                        <input type="text" value="<?= e($user['nik'] ?? '') ?>" readonly class="w-full px-4 py-2 border rounded-lg bg-gray-50">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Username Login</label>
                        <input type="text" value="<?= e($user['username'] ?? '') ?>" readonly class="w-full px-4 py-2 border rounded-lg bg-gray-50">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                        <input type="email" name="email" value="<?= e($user['email'] ?? '') ?>" class="w-full px-4 py-2 border rounded-lg">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Telepon</label>
                        <input type="text" name="phone" value="<?= e($user['phone'] ?? '') ?>" class="w-full px-4 py-2 border rounded-lg">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Unit Kerja</label>
                        <select name="unit_id" class="w-full px-4 py-2 border rounded-lg">
                            <option value="">-- Pilih Unit --</option>
                            <?php foreach ($unitOptions as $opt): ?>
                                <option value="<?= (int)$opt['id'] ?>" <?= ((int)($user['unit_id'] ?? 0) === (int)$opt['id']) ? 'selected' : '' ?>><?= e($opt['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Jabatan / Posisi</label>
                        <select name="position_name" class="w-full px-4 py-2 border rounded-lg">
                            <option value="">-- Pilih Jabatan --</option>
                            <?php foreach ($position_options as $label): ?>
                                <option value="<?= e($label) ?>" <?= (($user['position_name'] ?? '') === $label) ? 'selected' : '' ?>><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Profesi</label>
                        <select name="profession" class="w-full px-4 py-2 border rounded-lg">
                            <option value="">-- Pilih Profesi --</option>
                            <?php foreach ($profession_options as $key => $label): ?>
                                <option value="<?= e($key) ?>" <?= (($user['profession'] ?? '') === $key) ? 'selected' : '' ?>><?= e($label) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Role Sistem</label>
                        <input type="text" value="<?= e(ucfirst($user['role'] ?? 'user')) ?>" readonly class="w-full px-4 py-2 border rounded-lg bg-gray-50">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">Tanggal Bergabung</label>
                        <input type="date" name="join_date" value="<?= !empty($user['join_date']) ? e(date('Y-m-d', strtotime($user['join_date']))) : '' ?>" class="w-full px-4 py-2 border rounded-lg">
                        <p class="text-xs text-gray-500 mt-1">Dipakai untuk menghitung masa kerja.</p>
                    </div>
                    <div class="md:col-span-2 flex justify-end pt-2">
                        <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                            <i class="fas fa-save mr-2"></i> Simpan Profil
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div class="bg-white rounded-2xl shadow-md p-6">
            <h3 class="text-lg font-semibold mb-4"><i class="fas fa-key mr-2 text-blue-600"></i> Ubah Password Login</h3>
            <form method="POST" class="space-y-3">
                <input type="hidden" name="action" value="change_password">
                <input type="password" name="old_password" placeholder="Password lama" class="w-full px-4 py-2 border rounded-lg" required>
                <input type="password" name="new_password" placeholder="Password baru minimal 6 karakter" class="w-full px-4 py-2 border rounded-lg" required>
                <input type="password" name="confirm_password" placeholder="Konfirmasi password baru" class="w-full px-4 py-2 border rounded-lg" required>
                <button type="submit" class="w-full px-4 py-2 bg-slate-900 text-white rounded-lg hover:bg-slate-800">Simpan Password</button>
            </form>
        </div>
        <div class="bg-white rounded-2xl shadow-md p-6">
            <h3 class="text-lg font-semibold mb-4"><i class="fas fa-shield-alt mr-2 text-green-600"></i> Passcode Edit/Hapus Pribadi</h3>
            <p class="text-sm text-gray-500 mb-3">Default awal: <b>1234</b>. Setiap user sebaiknya mengganti passcode sendiri.</p>
            <form method="POST" class="space-y-3">
                <input type="hidden" name="action" value="change_passcode">
                <input type="password" name="old_passcode" placeholder="Passcode lama" class="w-full px-4 py-2 border rounded-lg" required>
                <input type="password" name="new_passcode" placeholder="Passcode baru 4-8 digit angka" class="w-full px-4 py-2 border rounded-lg" required>
                <input type="password" name="confirm_passcode" placeholder="Konfirmasi passcode baru" class="w-full px-4 py-2 border rounded-lg" required>
                <button type="submit" class="w-full px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Simpan Passcode</button>
            </form>
        </div>
    </div>

    <div class="bg-white rounded-2xl shadow-md p-6">
        <h3 class="text-lg font-semibold mb-3 flex items-center"><i class="fas fa-info-circle mr-2 text-blue-600"></i> Informasi</h3>
        <p class="text-gray-600 text-sm">Password digunakan untuk login. Passcode digunakan sebagai lapisan pengaman saat melakukan aksi edit/hapus di modul yang sudah diproteksi.</p>
    </div>
</div>
