<?php
session_start();
require_once '../config/config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get members requiring renewal (expired or expiring within 60 days)
    $stmt = $conn->prepare("
        SELECT 
            id,
            kso_id,
            name,
            membership_type,
            membership_expiry_date as expiry_date,
            email,
            phone,
            DATEDIFF(membership_expiry_date, CURDATE()) as days_until_expiry
        FROM members 
        WHERE status = 'active' 
        AND membership_expiry_date <= DATE_ADD(CURDATE(), INTERVAL 60 DAY)
        ORDER BY membership_expiry_date ASC
    ");
    $stmt->execute();
    $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'members' => $members
    ]);
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
?>
