<?php
/**
 * Get Assignment API Endpoint
 * 
 * Retrieves a single assignment by ID
 */

// Initialize the session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Include database connection
require_once __DIR__ . '/../../config/db_connect.php';

// Check authentication
if (!isset($_SESSION['admin_id'])) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Authentication required'
    ]);
    exit;
}

$admin_id = $_SESSION['admin_id'];

// Check if assignment ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Assignment ID is required'
    ]);
    exit;
}

$assignment_id = intval($_GET['id']);

try {
    // Get assignment details
    $query = "
        SELECT a.*, 
               m.kso_id, 
               CONCAT(m.first_name, ' ', m.last_name) as member_name,
               admin.username as assigned_by_name
        FROM admin_assignments a
        INNER JOIN members m ON a.member_id = m.id
        INNER JOIN admin_users admin ON a.assigned_by = admin.id
        WHERE a.id = ? AND (a.assigned_to = ? OR a.assigned_by = ?)
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param('iii', $assignment_id, $admin_id, $admin_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => 'Assignment not found or you do not have permission to view it'
        ]);
        exit;
    }
    
    $assignment = $result->fetch_assoc();
    
    // Get assignment history
    $query = "
        SELECT h.*, admin.username as updated_by_name
        FROM member_approval_history h
        INNER JOIN admin_users admin ON h.updated_by = admin.id
        WHERE h.assignment_id = ?
        ORDER BY h.created_at DESC
    ";
    
    $stmt = $conn->prepare($query);
    $stmt->bind_param('i', $assignment_id);
    $stmt->execute();
    $history_result = $stmt->get_result();
    
    $history = [];
    while ($row = $history_result->fetch_assoc()) {
        $history[] = $row;
    }
    
    $assignment['history'] = $history;
    
    // Return assignment
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'data' => $assignment
    ]);
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Error retrieving assignment: ' . $e->getMessage()
    ]);
}
