<?php
/**
 * AJAX Handler - Get Report Details
 * GHAMECC Choir Management Platform
 */

// Include authentication functions
require_once '../../includes/auth.php';

// Include database functions
require_once '../../config/database.php';

// Require login
requireLogin();

// Get user information and role
$userId = $_SESSION['user_id'];
$userInfo = fetchRow("SELECT u.*, r.role_key FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?", [$userId]);

// Check if report ID is provided
if (!isset($_GET['report_id']) || !is_numeric($_GET['report_id'])) {
    echo '<div class="alert alert-danger">Invalid report ID.</div>';
    exit;
}

$reportId = (int)$_GET['report_id'];

// Determine user's level in hierarchy
$userLevel = '';
$userEntityId = 0;

// Get user's associated entity (society, circuit, diocese)
if (in_array($userInfo['role_key'], ['choirmaster', 'society_secretary', 'society_treasurer'])) {
    $userLevel = 'society';
    
    // First check if user has society_id directly in the session
    if (isset($_SESSION['society_id']) && !empty($_SESSION['society_id'])) {
        $userEntityId = $_SESSION['society_id'];
    } else {
        // Try to get society from user record directly
        $userEntityId = $userInfo['society_id'] ?? 0;
    }
} elseif (in_array($userInfo['role_key'], ['circuit_chairman', 'circuit_secretary', 'circuit_dom', 'circuit_treasurer'])) {
    $userLevel = 'circuit';
    
    // First check if user has circuit_id directly in the session
    if (isset($_SESSION['circuit_id']) && !empty($_SESSION['circuit_id'])) {
        $userEntityId = $_SESSION['circuit_id'];
    } else {
        // Try to get circuit from user record directly
        $userEntityId = $userInfo['circuit_id'] ?? 0;
    }
} elseif (in_array($userInfo['role_key'], ['diocesan_chairman', 'diocesan_secretary', 'diocesan_dom', 'diocesan_treasurer'])) {
    $userLevel = 'diocese';
    
    // First check if user has diocese_id directly in the session
    if (isset($_SESSION['diocese_id']) && !empty($_SESSION['diocese_id'])) {
        $userEntityId = $_SESSION['diocese_id'];
    } else {
        // Try to get diocese from user record directly
        $userEntityId = $userInfo['diocese_id'] ?? 0;
    }
} elseif (in_array($userInfo['role_key'], ['admin'])) {
    $userLevel = 'connexional';
    $userEntityId = 1; // Assuming there's only one connexional level
}

// Get report details
$report = fetchRow("SELECT r.*, 
                        rt.name as report_type_name,
                        u.full_name as submitter_name, 
                        u.profile_image as submitter_image,
                        CASE 
                            WHEN r.source_type = 'society' THEN (SELECT name FROM societies WHERE id = r.source_id)
                            WHEN r.source_type = 'circuit' THEN (SELECT name FROM circuits WHERE id = r.source_id)
                            WHEN r.source_type = 'diocese' THEN (SELECT name FROM dioceses WHERE id = r.source_id)
                            ELSE 'Admin'
                        END as source_name
                    FROM reports r
                    JOIN users u ON r.submitted_by = u.id
                    LEFT JOIN report_types rt ON r.report_type_id = rt.id
                    WHERE r.id = ?", [$reportId]);

if (!$report) {
    echo '<div class="alert alert-danger">Report not found.</div>';
    exit;
}

// Check if user has permission to view this report
$hasPermission = false;

// Debug logging for permission check
logDebug("Permission check for report", [
    'user_id' => $userId,
    'user_role' => $userInfo['role_key'],
    'user_level' => $userLevel,
    'user_entity_id' => $userEntityId,
    'report_id' => $reportId,
    'report_source_type' => $report['source_type'],
    'report_source_id' => $report['source_id'],
    'report_target_type' => $report['target_type'],
    'report_target_id' => $report['target_id'],
    'report_submitted_by' => $report['submitted_by']
]);

// Admin can view all reports
if (in_array($userInfo['role_key'], ['admin'])) {
    $hasPermission = true;
    logDebug("Permission granted: Admin user");
}
// If user is the report submitter
elseif ($report['submitted_by'] == $userId) {
    $hasPermission = true;
    logDebug("Permission granted: Report submitter");
}
// If report is targeted to user's level and entity
elseif ($report['target_type'] == $userLevel && $report['target_id'] == $userEntityId) {
    $hasPermission = true;
    logDebug("Permission granted: Report targeted to user's level and entity");
}
// If user is from a circuit and report is from a society in their circuit
elseif ($userLevel == 'circuit' && $report['source_type'] == 'society') {
    $societyCircuit = fetchRow("SELECT circuit_id FROM societies WHERE id = ?", [$report['source_id']]);
    logDebug("Circuit permission check", [
        'society_id' => $report['source_id'],
        'society_circuit_id' => $societyCircuit ? $societyCircuit['circuit_id'] : 'not found',
        'user_circuit_id' => $userEntityId
    ]);
    if ($societyCircuit && $societyCircuit['circuit_id'] == $userEntityId) {
        $hasPermission = true;
        logDebug("Permission granted: Circuit user viewing society report from their circuit");
    }
}
// If user is from a diocese and report is from a circuit in their diocese
elseif ($userLevel == 'diocese' && $report['source_type'] == 'circuit') {
    $circuitDiocese = fetchRow("SELECT diocese_id FROM circuits WHERE id = ?", [$report['source_id']]);
    if ($circuitDiocese && $circuitDiocese['diocese_id'] == $userEntityId) {
        $hasPermission = true;
        logDebug("Permission granted: Diocese user viewing circuit report from their diocese");
    }
}

if (!$hasPermission) {
    logError("Permission denied for report access", [
        'user_id' => $userId,
        'user_role' => $userInfo['role_key'],
        'user_level' => $userLevel,
        'user_entity_id' => $userEntityId,
        'report_id' => $reportId
    ]);
    echo '<div class="alert alert-danger">You don\'t have permission to view this report.</div>';
    exit;
}

// Check if report_responses table exists
$responseTableExists = false;
$checkTable = fetchRow("SHOW TABLES LIKE 'report_responses'");
if ($checkTable) {
    $responseTableExists = true;
    
    // Get report responses if table exists
    $responses = fetchRows("SELECT rr.*, u.full_name, u.profile_image, r.role_key
                           FROM report_responses rr
                           JOIN users u ON rr.user_id = u.id
                           JOIN roles r ON u.role_id = r.id
                           WHERE rr.report_id = ?
                           ORDER BY rr.created_at ASC", [$reportId]);
} else {
    $responses = [];
}

// Format date
$createdDate = date('F j, Y \a\t g:i a', strtotime($report['created_at']));
?>

<div class="report-details">
    <div class="row mb-4">
        <div class="col-md-8">
            <h4><?php echo htmlspecialchars($report['title']); ?></h4>
            <div class="text-muted mb-2">
                <strong>Type:</strong> <?php echo htmlspecialchars($report['report_type_name'] ?? 'Unknown'); ?><br>
                <strong>From:</strong> <?php echo htmlspecialchars($report['source_name']); ?><br>
                <strong>Submitted:</strong> <?php echo $createdDate; ?><br>
                <strong>Status:</strong> 
                <span class="badge <?php echo getStatusBadgeClass($report['status']); ?>">
                    <?php echo ucfirst($report['status']); ?>
                </span>
            </div>
        </div>
        <div class="col-md-4 text-end">
            <div class="d-flex align-items-center justify-content-end">
                <div class="me-2">
                    <img src="<?php echo !empty($report['submitter_image']) ? '../uploads/profiles/' . $report['submitter_image'] : '../assets/img/default-profile.png'; ?>" 
                         class="rounded-circle" width="40" height="40" alt="Submitter">
                </div>
                <div class="text-start">
                    <div><?php echo htmlspecialchars($report['submitter_name']); ?></div>
                    <small class="text-muted">Submitter</small>
                </div>
            </div>
        </div>
    </div>
    
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="card-title mb-0">Report Content</h5>
        </div>
        <div class="card-body">
            <?php echo $report['content']; ?>
        </div>
    </div>
    
    <?php if (!empty($report['file_path'])): ?>
    <div class="card mb-4">
        <div class="card-header">
            <h5 class="card-title mb-0">Attachments</h5>
        </div>
        <div class="card-body">
            <a href="../../uploads/reports/<?php echo $report['file_path']; ?>" class="btn btn-sm btn-outline-primary" target="_blank">
                <i class="fas fa-file me-1"></i> View Attachment
            </a>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if ($responseTableExists && !empty($responses)): ?>
    <div class="card">
        <div class="card-header">
            <h5 class="card-title mb-0">Responses</h5>
        </div>
        <div class="card-body">
            <?php foreach ($responses as $response): ?>
                <div class="d-flex mb-3 pb-3 border-bottom">
                    <div class="me-3">
                        <img src="<?php echo !empty($response['profile_image']) ? '../uploads/profiles/' . $response['profile_image'] : '../assets/img/default-profile.png'; ?>" 
                             class="rounded-circle" width="40" height="40" alt="User">
                    </div>
                    <div class="flex-grow-1">
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <div>
                                <strong><?php echo htmlspecialchars($response['full_name']); ?></strong>
                                <span class="badge bg-secondary ms-2"><?php echo ucwords(str_replace('_', ' ', $response['role_key'])); ?></span>
                            </div>
                            <small class="text-muted"><?php echo date('M j, Y g:i a', strtotime($response['created_at'])); ?></small>
                        </div>
                        <div><?php echo $response['content']; ?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
</div>

<?php
// Helper function to get appropriate badge class based on status
function getStatusBadgeClass($status) {
    switch (strtolower($status)) {
        case 'draft':
            return 'bg-secondary';
        case 'submitted':
            return 'bg-info';
        case 'approved':
            return 'bg-success';
        case 'rejected':
            return 'bg-danger';
        case 'reviewed':
            return 'bg-warning';
        default:
            return 'bg-secondary';
    }
}
?>
