<?php
require_once(__DIR__ . '/../../session.php');

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

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

    $action = $_POST['action'] ?? '';

    switch ($action) {
        case 'profile':
            $adminId = $_POST['id'];
            $fullname = $_POST['fullname'];
            $username = $_POST['username'];

            if (empty($fullname) || empty($username)) {
                echo json_encode(['status' => 'error', 'message' => "Nama lengkap dan username wajib diisi."]);
                exit;
            }

            $updateProfile = "UPDATE admin SET fullname = :fullname, username = :username WHERE id = :id";
            $stmt = $db->prepare($updateProfile);

            $stmt->bindParam(':fullname', $fullname);
            $stmt->bindParam(':username', $username);
            $stmt->bindParam(':id', $adminId, PDO::PARAM_INT);
            $stmt->execute();

            if ($stmt->rowCount()) {
                echo json_encode(['status' => 'success', 'message' => "Profil berhasil diperbarui."]);
            } else {
                echo json_encode(['status' => 'error', 'message' => "Tidak ada perubahan atau pembaruan gagal."]);
            }
            break;

        case 'password':
            $adminId = $_POST['id'];
            $new_password = $_POST['new_password'];
            $confirm_password = $_POST['confirm_password'];

            if (empty($new_password) || empty($confirm_password)) {
                echo json_encode(['status' => 'error', 'message' => "Kata sandi baru dan konfirmasi wajib diisi."]);
                exit;
            }

            if ($new_password !== $confirm_password) {
                echo json_encode(['status' => 'error', 'message' => "Kata sandi tidak cocok."]);
                exit;
            }

            $passwordHash = password_hash($confirm_password, PASSWORD_DEFAULT);
            $updatePassword = "UPDATE admin SET password = :password WHERE id = :id";
            $stmt = $db->prepare($updatePassword);

            $stmt->bindParam(':password', $passwordHash);
            $stmt->bindParam(':id', $adminId, PDO::PARAM_INT);
            $stmt->execute();

            if ($stmt->rowCount()) {
                echo json_encode(['status' => 'success', 'message' => "Kata sandi berhasil diperbarui."]);
            } else {
                echo json_encode(['status' => 'error', 'message' => "Pembaruan gagal."]);
            }
            break;

        default:
            echo json_encode(['status' => 'error', 'message' => "Aksi tidak valid."]);
            break;
    }
} else {
    echo json_encode(['status' => 'error', 'message' => "Metode permintaan tidak valid."]);
}
