<?php
/**
 * AJAX Handler - Get Circuit Report Details
 * Dedicated handler for circuit-level users
 * 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 user is a circuit-level user
$allowedRoles = ['circuit_chairman', 'circuit_secretary', 'circuit_music_director', 'circuit_treasurer'];
if (!in_array($userInfo['role_key'], $allowedRoles)) {
    echo '<div class="alert alert-danger">Access denied. This handler is for circuit-level users only.</div>';
    exit;
}

// 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'];

// Get user's circuit ID
$userCircuitId = 0;
if (isset($_SESSION['circuit_id']) && !empty($_SESSION['circuit_id'])) {
    $userCircuitId = $_SESSION['circuit_id'];
} else {
    $userCircuitId = $userInfo['circuit_id'] ?? 0;
}

logDebug("Circuit user accessing report", [
    'user_id' => $userId,
    'user_role' => $userInfo['role_key'],
    'user_circuit_id' => $userCircuitId,
    'report_id' => $reportId
]);

// 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 LOWER(r.source_type) = 'society' THEN (SELECT name FROM societies WHERE id = r.source_id)
                            WHEN LOWER(r.source_type) = 'circuit' THEN (SELECT name FROM circuits WHERE id = r.source_id)
                            WHEN LOWER(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("Circuit permission check for report", [
    'user_id' => $userId,
    'user_role' => $userInfo['role_key'],
    'user_circuit_id' => $userCircuitId,
    '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']
]);

// If user is the report submitter
if ($report['submitted_by'] == $userId) {
    $hasPermission = true;
    logDebug("Permission granted: Report submitter");
}
// If report is targeted to circuit and matches user's circuit
elseif (strtolower($report['target_type']) == 'circuit' && $report['target_id'] == $userCircuitId) {
    $hasPermission = true;
    logDebug("Permission granted: Report targeted to user's circuit");
}
// If report is from a society in user's circuit
elseif (strtolower($report['source_type']) == 'society') {
    $societyCircuit = fetchRow("SELECT circuit_id FROM societies WHERE id = ?", [$report['source_id']]);
    logDebug("Society circuit check", [
        'society_id' => $report['source_id'],
        'society_circuit_id' => $societyCircuit ? $societyCircuit['circuit_id'] : 'not found',
        'user_circuit_id' => $userCircuitId
    ]);
    if ($societyCircuit && $societyCircuit['circuit_id'] == $userCircuitId) {
        $hasPermission = true;
        logDebug("Permission granted: Circuit user viewing society report from their circuit");
    }
}
// If report is from user's own circuit
elseif (strtolower($report['source_type']) == 'circuit' && $report['source_id'] == $userCircuitId) {
    $hasPermission = true;
    logDebug("Permission granted: Report from user's own circuit");
}

if (!$hasPermission) {
    logError("Circuit permission denied for report access", [
        'user_id' => $userId,
        'user_role' => $userInfo['role_key'],
        'user_circuit_id' => $userCircuitId,
        'report_id' => $reportId,
        'report_source_type' => $report['source_type'],
        'report_target_type' => $report['target_type']
    ]);
    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">
                <i class="fas fa-calendar me-1"></i> <?php echo $createdDate; ?>
            </div>
            <div class="mb-2">
                <span class="badge bg-primary me-2"><?php echo htmlspecialchars($report['report_type_name']); ?></span>
                <span class="badge bg-secondary"><?php echo htmlspecialchars($report['status']); ?></span>
            </div>
        </div>
        <div class="col-md-4 text-end">
            <div class="d-flex align-items-center justify-content-end">
                <img src="<?php echo !empty($report['submitter_image']) ? '../../uploads/profiles/' . $report['submitter_image'] : '../../assets/img/default-profile.png'; ?>" 
                     class="rounded-circle me-2" width="40" height="40" alt="Submitter">
                <div>
                    <div class="fw-bold"><?php echo htmlspecialchars($report['submitter_name']); ?></div>
                    <div class="text-muted small">From: <?php echo htmlspecialchars($report['source_name']); ?></div>
                </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-start mb-2">
                            <div>
                                <strong><?php echo htmlspecialchars($response['full_name']); ?></strong>
                                <span class="badge bg-info ms-2"><?php echo htmlspecialchars($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 nl2br(htmlspecialchars($response['response_text'])); ?></div>
                        <?php if (!empty($response['attachment'])): ?>
                            <div class="mt-2">
                                <a href="../../uploads/reports/responses/<?php echo $response['attachment']; ?>" class="btn btn-sm btn-outline-secondary" target="_blank">
                                    <i class="fas fa-paperclip me-1"></i> View Attachment
                                </a>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Response Form for Circuit Users -->
    <div class="card mt-4">
        <div class="card-header">
            <h5 class="card-title mb-0">Add Response</h5>
        </div>
        <div class="card-body">
            <form id="responseForm" enctype="multipart/form-data">
                <input type="hidden" name="report_id" value="<?php echo $reportId; ?>">
                <div class="mb-3">
                    <label for="response_text" class="form-label">Response</label>
                    <textarea class="form-control" id="response_text" name="response_text" rows="4" required></textarea>
                </div>
                <div class="mb-3">
                    <label for="response_attachment" class="form-label">Attachment (Optional)</label>
                    <input type="file" class="form-control" id="response_attachment" name="response_attachment">
                </div>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-paper-plane me-1"></i> Submit Response
                </button>
            </form>
        </div>
    </div>
</div>

<script>
console.log('Script loaded, looking for responseForm...');
const responseForm = document.getElementById('responseForm');
console.log('Response form found:', responseForm);

if (responseForm) {
    responseForm.addEventListener('submit', function(e) {
        console.log('Form submit event triggered');
        e.preventDefault();
        
        const formData = new FormData(this);
        const submitButton = this.querySelector('button[type="submit"]');
        const originalText = submitButton.innerHTML;
        
        console.log('Form data:', {
            report_id: formData.get('report_id'),
            response_text: formData.get('response_text'),
            has_attachment: formData.get('response_attachment') ? 'yes' : 'no'
        });
        
        // Show loading state
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i> Submitting...';
        
        console.log('Making fetch request to submit_response.php');
        
        fetch('submit_response.php', {
            method: 'POST',
            body: formData
        })
        .then(response => {
            console.log('Response received:', response.status, response.statusText);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.text(); // Get as text first to see what we're getting
        })
        .then(text => {
            console.log('Raw response text:', text);
            try {
                const data = JSON.parse(text);
                console.log('Parsed JSON data:', data);
                
                if (data.success) {
                    // Show success message
                    alert('Response submitted successfully!');
                    // Clear the form
                    document.getElementById('response_text').value = '';
                    document.getElementById('response_attachment').value = '';
                    // Reload the report details to show the new response
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            } catch (parseError) {
                console.error('JSON parse error:', parseError);
                console.error('Response was not valid JSON:', text);
                alert('Server returned invalid response. Check console for details.');
            }
        })
        .catch(error => {
            console.error('Fetch error:', error);
            alert('An error occurred while submitting the response. Check console for details.');
        })
        .finally(() => {
            // Restore button state
            submitButton.disabled = false;
            submitButton.innerHTML = originalText;
        });
    });
} else {
    console.error('Response form not found!');
}

// Also add a click handler to the button directly as backup
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM loaded, checking for submit button...');
    const submitBtn = document.querySelector('#responseForm button[type="submit"]');
    console.log('Submit button found:', submitBtn);
    
    if (submitBtn) {
        submitBtn.addEventListener('click', function(e) {
            console.log('Submit button clicked directly');
        });
    }
});
</script>
