<?php
/**
 * API: Get assignments list
 * 
 * This endpoint returns assignments with filtering and pagination
 */

require_once '../../config/database.php';
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'data' => [],
    'message' => 'Error retrieving assignments'
];

try {
    $db = new Database();
    $conn = $db->getConnection();
    
    // Get parameters with defaults
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $offset = ($page - 1) * $limit;
    
    // Build the query with filters
    $params = [];
    $whereClause = [];
    
    // Default to showing only active assignments
    if (!isset($_GET['status'])) {
        $whereClause[] = "aa.status != 'completed'";
    }
    
    // Filter by current admin if requested
    if (isset($_GET['my_assignments']) && $_GET['my_assignments'] == 1) {
        $whereClause[] = "aa.assigned_to = :current_admin_id";
        $params[':current_admin_id'] = $_SESSION['admin_id'];
    }
    
    // Apply filters if provided
    if (isset($_GET['status']) && !empty($_GET['status'])) {
        $whereClause[] = "aa.status = :status";
        $params[':status'] = $_GET['status'];
    }
    
    if (isset($_GET['priority']) && !empty($_GET['priority'])) {
        $whereClause[] = "aa.priority = :priority";
        $params[':priority'] = $_GET['priority'];
    }
    
    if (isset($_GET['assignment_type']) && !empty($_GET['assignment_type'])) {
        $whereClause[] = "aa.assignment_type = :assignment_type";
        $params[':assignment_type'] = $_GET['assignment_type'];
    }
    
    if (isset($_GET['assigned_to']) && !empty($_GET['assigned_to'])) {
        $whereClause[] = "aa.assigned_to = :assigned_to";
        $params[':assigned_to'] = $_GET['assigned_to'];
    }
    
    if (isset($_GET['assigned_by']) && !empty($_GET['assigned_by'])) {
        $whereClause[] = "aa.assigned_by = :assigned_by";
        $params[':assigned_by'] = $_GET['assigned_by'];
    }
    
    if (isset($_GET['member_id']) && !empty($_GET['member_id'])) {
        $whereClause[] = "aa.member_id = :member_id";
        $params[':member_id'] = $_GET['member_id'];
    }
    
    if (isset($_GET['search']) && !empty($_GET['search'])) {
        $whereClause[] = "(m.first_name LIKE :search OR m.last_name LIKE :search OR m.kso_id LIKE :search OR CONCAT(m.first_name, ' ', m.last_name) LIKE :search)";
        $params[':search'] = '%' . $_GET['search'] . '%';
    }
    
    // Combine where clauses
    $whereStr = !empty($whereClause) ? "WHERE " . implode(" AND ", $whereClause) : "";
    
    // Get total count for pagination
    $countQuery = "SELECT COUNT(*) as total FROM admin_assignments aa $whereStr";
    $stmt = $conn->prepare($countQuery);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->execute();
    $totalCount = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    
    // Main query
    $query = "SELECT 
                aa.*,
                m.kso_id, 
                CONCAT(m.first_name, ' ', m.last_name) as member_name,
                CONCAT(a_to.first_name, ' ', a_to.last_name) as assigned_to_name,
                CONCAT(a_by.first_name, ' ', a_by.last_name) as assigned_by_name
              FROM admin_assignments aa
              JOIN members m ON aa.member_id = m.id
              JOIN admins a_to ON aa.assigned_to = a_to.id
              JOIN admins a_by ON aa.assigned_by = a_by.id
              $whereStr
              ORDER BY 
                CASE 
                  WHEN aa.status = 'overdue' THEN 1
                  WHEN aa.priority = 'urgent' THEN 2
                  WHEN aa.priority = 'high' THEN 3
                  WHEN aa.priority = 'normal' THEN 4
                  WHEN aa.priority = 'low' THEN 5
                  ELSE 6
                END,
                aa.created_at DESC
              LIMIT :offset, :limit";
    
    $stmt = $conn->prepare($query);
    foreach ($params as $key => $value) {
        $stmt->bindValue($key, $value);
    }
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    
    $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Format the response
    $response = [
        'success' => true,
        'data' => [
            'assignments' => $assignments,
            'pagination' => [
                'total' => $totalCount,
                'page' => $page,
                'limit' => $limit,
                'pages' => ceil($totalCount / $limit)
            ]
        ],
        'message' => 'Assignments retrieved successfully'
    ];
    
} catch (PDOException $e) {
    $response['message'] = 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
    $response['message'] = 'Error: ' . $e->getMessage();
}

// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);
exit;
