<?php
// cek_iuran.php
header("Content-Type: application/json; charset=UTF-8");
require 'security.php';
require 'logger.php';
require 'db.php';

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

// Mendapatkan token dari header Authorization
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    $authorizationHeader = $headers['Authorization'];
    $token = str_replace("Bearer ", "", $authorizationHeader);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    log_activity("Authorization header missing in cek_iuran.php");
    exit;
}

try {
    // 1) Validasi token dan ambil user_id
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();
    if (!$tokenData) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        log_activity("Invalid or expired token in cek_iuran.php");
        exit;
    }
    $user_id = $tokenData['user_id'];

    // 2) Ambil daftar iuran yang aktif untuk bulan saat ini
    $currentMonth = date('Y-m'); // Format: YYYY-MM (bulan berjalan)
    $stmt = $pdo->prepare("SELECT id, nama, nominal, periode FROM jenis_iuran WHERE status = 'aktif' AND DATE_FORMAT(periode, '%Y-%m') = ?");
    $stmt->execute([$currentMonth]);
    $jenisIuran = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (!$jenisIuran) {
        http_response_code(404);
        echo json_encode(['error' => 'No active iuran found for the current month']);
        log_activity("No active iuran found for the current month in cek_iuran.php");
        exit;
    }

    // 3) Ambil daftar iuran yang sudah dibayar bulan ini
    $stmt = $pdo->prepare("SELECT iuran_id FROM pembayaran_iuran WHERE user_id = ? AND DATE_FORMAT(tanggal_bayar, '%Y-%m') = ?");
    $stmt->execute([$user_id, $currentMonth]);
    $iuranDibayar = $stmt->fetchAll(PDO::FETCH_COLUMN);

    // 4) Filter iuran yang BELUM dibayar
    $iuranBelumDibayar = array_values(array_filter($jenisIuran, function ($iuran) use ($iuranDibayar) {
        return !in_array($iuran['id'], $iuranDibayar);
    }));

    // 5) Urutkan iuran berdasarkan tanggal periode terlebih dahulu, lalu berdasarkan nama
    usort($iuranBelumDibayar, function ($a, $b) {
        $dateComparison = strcmp($a['periode'], $b['periode']);
        return $dateComparison !== 0 ? $dateComparison : strcmp($a['nama'], $b['nama']);
    });

    // 6) Kirim response
    http_response_code(200);
    echo json_encode([
        'user_id' => $user_id,
        'iuran_belum_dibayar' => $iuranBelumDibayar
    ]);
    log_activity("Checked unpaid iuran for user_id: $user_id");
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("cek_iuran.php error: " . $e->getMessage());
    exit;
}
