<?php
require_once __DIR__ . '/db.php';
require_login();

$userId = (int) ($_SESSION['user_id'] ?? 0);
$actionType = $_POST['action_type'] ?? '';

if ($actionType === 'profile') {
    $nama = trim($_POST['nama'] ?? '');
    $emel = trim($_POST['emel'] ?? '');
    $jabatan = trim($_POST['jabatan'] ?? '');

    if (!in_array($jabatan, audit_bahagian_list(), true)) {
        header('Location: profile_pengguna.php?error=invalid_unit');
        exit();
    }

    $checkStmt = $conn->prepare("SELECT id FROM users WHERE emel = ? AND id <> ? LIMIT 1");
    $checkStmt->bind_param('si', $emel, $userId);
    $checkStmt->execute();
    if ($checkStmt->get_result()->fetch_assoc()) {
        header('Location: profile_pengguna.php?error=email_exists');
        exit();
    }

    $stmt = $conn->prepare("UPDATE users SET nama = ?, emel = ?, jabatan = ? WHERE id = ?");
    $stmt->bind_param('sssi', $nama, $emel, $jabatan, $userId);
    $stmt->execute();

    $_SESSION['user_nama'] = $nama;
    $_SESSION['user_emel'] = $emel;
    $_SESSION['user_jabatan'] = $jabatan;
    add_current_user_log($conn, 'Mengemaskini profil pengguna');

    header('Location: profile_pengguna.php?success=profile_updated');
    exit();
}

if ($actionType === 'password') {
    $oldPassword = $_POST['old_password'] ?? '';
    $newPassword = $_POST['new_password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';

    if ($newPassword !== $confirmPassword) {
        header('Location: profile_pengguna.php?error=password_mismatch');
        exit();
    }

    $stmt = $conn->prepare("SELECT password FROM users WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $user = $stmt->get_result()->fetch_assoc();

    if (!$user || !password_verify($oldPassword, $user['password'])) {
        header('Location: profile_pengguna.php?error=wrong_password');
        exit();
    }

    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
    $update = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
    $update->bind_param('si', $hashedPassword, $userId);
    $update->execute();
    add_current_user_log($conn, 'Mengemaskini kata laluan');

    header('Location: profile_pengguna.php?success=password_updated');
    exit();
}

header('Location: profile_pengguna.php');
exit();
