<?php
require_once '../../config/database.php';
require_once '../../config/auth_enhanced.php';

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

// Check authentication
if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

try {
    $database = new Database();
    $conn = $database->getConnection();
    
    // Get filter parameters
    $status = isset($_GET['status']) ? $_GET['status'] : '';
    $assignment = isset($_GET['assignment']) ? $_GET['assignment'] : '';
    $dateRange = isset($_GET['dateRange']) ? $_GET['dateRange'] : '';
    $dateFrom = isset($_GET['dateFrom']) ? $_GET['dateFrom'] : '';
    $dateTo = isset($_GET['dateTo']) ? $_GET['dateTo'] : '';
    
    // Build the query
    $query = "SELECT m.*, 
                     a.first_name AS assigned_to_first_name, 
                     a.last_name AS assigned_to_last_name,
                     CONCAT(a.first_name, ' ', a.last_name) AS assigned_to_name
              FROM members m
              LEFT JOIN admins a ON m.assigned_to = a.id
              WHERE 1=1";
    $params = [];
    
    // Add status filter
    if (!empty($status)) {
        $query .= " AND m.status = ?";
        $params[] = $status;
    }
    
    // Add assignment filter
    if (!empty($assignment)) {
        switch ($assignment) {
            case 'assigned_to_me':
                $query .= " AND m.assigned_to = ?";
                $params[] = $_SESSION['admin_id'];
                break;
            case 'unassigned':
                $query .= " AND (m.assigned_to IS NULL OR m.assigned_to = 0)";
                break;
            case 'assigned_to_others':
                $query .= " AND m.assigned_to IS NOT NULL AND m.assigned_to != ?";
                $params[] = $_SESSION['admin_id'];
                break;
        }
    }
    
    // Add date range filter
    if (!empty($dateRange)) {
        switch ($dateRange) {
            case 'today':
                $query .= " AND DATE(m.created_at) = CURDATE()";
                break;
            case 'yesterday':
                $query .= " AND DATE(m.created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)";
                break;
            case 'this_week':
                $query .= " AND YEARWEEK(m.created_at) = YEARWEEK(CURDATE())";
                break;
            case 'this_month':
                $query .= " AND MONTH(m.created_at) = MONTH(CURDATE()) AND YEAR(m.created_at) = YEAR(CURDATE())";
                break;
            case 'custom':
                if (!empty($dateFrom)) {
                    $query .= " AND DATE(m.created_at) >= ?";
                    $params[] = $dateFrom;
                }
                if (!empty($dateTo)) {
                    $query .= " AND DATE(m.created_at) <= ?";
                    $params[] = $dateTo;
                }
                break;
        }
    }
    
    // Prepare and execute the query
    $stmt = $conn->prepare($query);
    
    if (!empty($params)) {
        $stmt->execute($params);
    } else {
        $stmt->execute();
    }
    
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get counts for different statuses
    $countQuery = "SELECT 
                     SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
                     SUM(CASE WHEN status = 'under_review' THEN 1 ELSE 0 END) as under_review,
                     SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected,
                     SUM(CASE WHEN status = 'approved' AND DATE(approved_at) = CURDATE() THEN 1 ELSE 0 END) as approved_today
                   FROM members";
    
    $countStmt = $conn->prepare($countQuery);
    $countStmt->execute();
    $counts = $countStmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $results,
        'counts' => $counts,
        'message' => 'Member approval data fetched successfully'
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
