<?php
require_once '../../config.php';
require_once '../../auth/check_auth.php';

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

try {
    $recipient_types = $_POST['recipient_types'] ?? [];
    
    if (empty($recipient_types)) {
        echo json_encode(['success' => true, 'recipients' => []]);
        exit();
    }
    
    $recipients = [];
    
    foreach ($recipient_types as $type) {
        switch ($type) {
            case 'all':
                $stmt = $pdo->prepare("
                    SELECT 
                        id,
                        CONCAT(first_name, ' ', last_name) as name,
                        email,
                        membership_type
                    FROM members 
                    WHERE status = 'active' AND email IS NOT NULL AND email != ''
                ");
                $stmt->execute();
                $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $recipients = array_merge($recipients, $members);
                break;
                
            case 'individual':
                $stmt = $pdo->prepare("
                    SELECT 
                        id,
                        CONCAT(first_name, ' ', last_name) as name,
                        email,
                        membership_type
                    FROM members 
                    WHERE status = 'active' 
                    AND membership_type = 'individual'
                    AND email IS NOT NULL AND email != ''
                ");
                $stmt->execute();
                $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $recipients = array_merge($recipients, $members);
                break;
                
            case 'family':
                $stmt = $pdo->prepare("
                    SELECT 
                        id,
                        CONCAT(first_name, ' ', last_name) as name,
                        email,
                        membership_type
                    FROM members 
                    WHERE status = 'active' 
                    AND membership_type = 'family'
                    AND email IS NOT NULL AND email != ''
                ");
                $stmt->execute();
                $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $recipients = array_merge($recipients, $members);
                break;
                
            case 'expiring':
                $stmt = $pdo->prepare("
                    SELECT 
                        id,
                        CONCAT(first_name, ' ', last_name) as name,
                        email,
                        membership_type
                    FROM members 
                    WHERE status = 'active' 
                    AND membership_expiry BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
                    AND email IS NOT NULL AND email != ''
                ");
                $stmt->execute();
                $members = $stmt->fetchAll(PDO::FETCH_ASSOC);
                $recipients = array_merge($recipients, $members);
                break;
        }
    }
    
    // Remove duplicates based on email
    $uniqueRecipients = [];
    $seenEmails = [];
    
    foreach ($recipients as $recipient) {
        if (!in_array($recipient['email'], $seenEmails)) {
            $uniqueRecipients[] = $recipient;
            $seenEmails[] = $recipient['email'];
        }
    }
    
    echo json_encode([
        'success' => true,
        'recipients' => $uniqueRecipients
    ]);
    
} catch (Exception $e) {
    error_log("Email Recipients Error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching recipients: ' . $e->getMessage()
    ]);
}
?>
