<?php
/**
 * api/update_account.php
 * Endpoint untuk memperbarui Email, Username, dan Password User
 */
session_start();
header('Content-Type: application/json');

// 1. Validasi Metode Request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Metode request tidak diizinkan.']);
    exit;
}

// 2. Validasi CSRF Token
$csrf_token = $_POST['csrf_token'] ?? '';
if (empty($csrf_token) || $csrf_token !== $_SESSION['csrf_token']) {
    echo json_encode(['status' => 'error', 'message' => 'Sesi tidak valid (CSRF Mismatch).']);
    exit;
}

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Akses ditolak. Silakan login.']);
    exit;
}

include '../config/database.php';

$user_id = $_SESSION['user_id'];
$email_baru = trim(strtolower($_POST['email'] ?? '')); // Ambil Input Email
$username_baru = trim($_POST['username'] ?? ''); 
$password_baru = trim($_POST['password'] ?? '');

// 3. Validasi Input
if (empty($email_baru) || empty($username_baru)) {
    echo json_encode(['status' => 'error', 'message' => 'Email dan Username tidak boleh kosong.']);
    exit;
}

if (preg_match('/\s/', $username_baru)) {
    echo json_encode(['status' => 'error', 'message' => 'Username tidak boleh mengandung spasi.']);
    exit;
}

try {
    // 4. CEK DUPLIKAT USERNAME
    $cek_username = mysqli_prepare($conn, "SELECT id FROM users WHERE username = ? AND id != ?");
    mysqli_stmt_bind_param($cek_username, "ss", $username_baru, $user_id);
    mysqli_stmt_execute($cek_username);
    mysqli_stmt_store_result($cek_username);
    
    if (mysqli_stmt_num_rows($cek_username) > 0) {
        echo json_encode(['status' => 'error', 'message' => 'Username sudah digunakan oleh pengguna lain. Silakan cari username yang berbeda.']);
        mysqli_stmt_close($cek_username);
        exit;
    }
    mysqli_stmt_close($cek_username);

    // 5. EKSEKUSI UPDATE (KOLOM DIUBAH MENJADI email_guru)
    if (!empty($password_baru)) {
        $hashed_password = password_hash($password_baru, PASSWORD_DEFAULT);
        $query = "UPDATE users SET email_guru = ?, username = ?, password = ? WHERE id = ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, "ssss", $email_baru, $username_baru, $hashed_password, $user_id);
    } else {
        $query = "UPDATE users SET email_guru = ?, username = ? WHERE id = ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, "sss", $email_baru, $username_baru, $user_id);
    }

    if (mysqli_stmt_execute($stmt)) {
        if (mysqli_stmt_affected_rows($stmt) > 0) {
            $_SESSION['nama'] = $username_baru; // Update sesi nama menjadi username baru
            echo json_encode(['status' => 'success', 'message' => 'Profil dan Username berhasil diperbarui!']);
        } else {
            echo json_encode(['status' => 'success', 'message' => 'Tidak ada perubahan data yang disimpan (Data sama).']);
        }
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan data ke database.']);
    }

    mysqli_stmt_close($stmt);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Terjadi kesalahan sistem: ' . $e->getMessage()]);
}

mysqli_close($conn);
?>