<?php
// admin_reports.php
header("Content-Type: application/json; charset=UTF-8");

// Inklusi file keamanan dan autentikasi
require 'security.php';
require 'logger.php';
require 'rate_limit.php';
require 'authenticate.php';

// Cek metode request
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on admin_reports.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Autentikasi: Hanya admin dan master_admin yang diizinkan
$user = authenticate($pdo, ['admin', 'master_admin']);

// Terapkan rate limiting spesifik endpoint jika diperlukan
$identifier = $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REQUEST_URI'];
rate_limit($pdo, 100, 60, $identifier);

// Contoh pengambilan laporan
try {
    // Jumlah anggota koperasi
    $stmt = $pdo->prepare("SELECT COUNT(*) as total_members FROM users");
    $stmt->execute();
    $total_members = $stmt->fetch()['total_members'];

    // Jumlah koperasi
    $stmt = $pdo->prepare("SELECT COUNT(*) as total_cooperatives FROM cooperatives");
    $stmt->execute();
    $total_cooperatives = $stmt->fetch()['total_cooperatives'];

    // Jumlah iuran
    $stmt = $pdo->prepare("SELECT COUNT(*) as total_dues FROM dues");
    $stmt->execute();
    $total_dues = $stmt->fetch()['total_dues'];

    // Kembalikan laporan
    http_response_code(200);
    echo json_encode([
        'total_members' => $total_members,
        'total_cooperatives' => $total_cooperatives,
        'total_dues' => $total_dues
    ]);

    log_activity("Admin reports accessed by user_id: " . $user['id']);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("admin_reports.php server error: " . $e->getMessage());
    exit;
}
?>
