<?php
/**
 * AJAX Handler - Get Diocesan Report Details
 * Dedicated handler for diocesan-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 diocesan-level user
$allowedRoles = ['diocesan_chairman', 'diocesan_secretary', 'diocesan_music_director', 'diocesan_treasurer'];
if (!in_array($userInfo['role_key'], $allowedRoles)) {
    echo '<div class="alert alert-danger">Access denied. This handler is for diocesan-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 diocese ID
$userDioceseId = 0;
if (isset($_SESSION['diocese_id']) && !empty($_SESSION['diocese_id'])) {
    $userDioceseId = $_SESSION['diocese_id'];
} else {
    $userDioceseId = $userInfo['diocese_id'] ?? 0;
}

logDebug("Diocesan user accessing report", [
    'user_id' => $userId,
    'user_role' => $userInfo['role_key'],
    'user_diocese_id' => $userDioceseId,
    '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("Diocesan permission check for report", [
    'user_id' => $userId,
    'user_role' => $userInfo['role_key'],
    'user_diocese_id' => $userDioceseId,
    '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 diocese and matches user's diocese
elseif (strtolower($report['target_type']) == 'diocese' && $report['target_id'] == $userDioceseId) {
    $hasPermission = true;
    logDebug("Permission granted: Report targeted to user's diocese");
}
// If report is from a circuit in user's diocese
elseif (strtolower($report['source_type']) == 'circuit') {
    $circuitDiocese = fetchRow("SELECT diocese_id FROM circuits WHERE id = ?", [$report['source_id']]);
    logDebug("Circuit diocese check", [
        'circuit_id' => $report['source_id'],
        'circuit_diocese_id' => $circuitDiocese ? $circuitDiocese['diocese_id'] : 'not found',
        'user_diocese_id' => $userDioceseId
    ]);
    if ($circuitDiocese && $circuitDiocese['diocese_id'] == $userDioceseId) {
        $hasPermission = true;
        logDebug("Permission granted: Diocesan user viewing circuit report from their diocese");
    }
}
// If report is from a society in user's diocese
elseif (strtolower($report['source_type']) == 'society') {
    $societyDiocese = fetchRow("SELECT c.diocese_id FROM societies s JOIN circuits c ON s.circuit_id = c.id WHERE s.id = ?", [$report['source_id']]);
    logDebug("Society diocese check", [
        'society_id' => $report['source_id'],
        'society_diocese_id' => $societyDiocese ? $societyDiocese['diocese_id'] : 'not found',
        'user_diocese_id' => $userDioceseId
    ]);
    if ($societyDiocese && $societyDiocese['diocese_id'] == $userDioceseId) {
        $hasPermission = true;
        logDebug("Permission granted: Diocesan user viewing society report from their diocese");
    }
}
// If report is from user's own diocese
elseif (strtolower($report['source_type']) == 'diocese' && $report['source_id'] == $userDioceseId) {
    $hasPermission = true;
    logDebug("Permission granted: Report from user's own diocese");
}

if (!$hasPermission) {
    logError("Diocesan permission denied for report access", [
        'user_id' => $userId,
        'user_role' => $userInfo['role_key'],
        'user_diocese_id' => $userDioceseId,
        '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="modal-header">
    <h5 class="modal-title">
        <i class="fas fa-file-alt me-2"></i>
        <?php echo htmlspecialchars($report['title']); ?>
    </h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>

<div class="modal-body">
    <!-- Report Information -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card border-0 bg-light">
                <div class="card-body p-3">
                    <h6 class="card-title mb-2">
                        <i class="fas fa-info-circle text-primary me-1"></i>
                        Report Information
                    </h6>
                    <p class="mb-1"><strong>Type:</strong> <?php echo htmlspecialchars($report['report_type_name'] ?? 'N/A'); ?></p>
                    <p class="mb-1"><strong>From:</strong> <?php echo htmlspecialchars($report['source_name']); ?></p>
                    <p class="mb-1"><strong>Status:</strong> 
                        <span class="badge bg-<?php echo $report['status'] == 'Draft' ? 'secondary' : 'success'; ?>">
                            <?php echo htmlspecialchars($report['status']); ?>
                        </span>
                    </p>
                    <p class="mb-0"><strong>Submitted:</strong> <?php echo $createdDate; ?></p>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card border-0 bg-light">
                <div class="card-body p-3">
                    <h6 class="card-title mb-2">
                        <i class="fas fa-user text-primary me-1"></i>
                        Submitted By
                    </h6>
                    <div class="d-flex align-items-center">
                        <?php if (!empty($report['submitter_image'])): ?>
                            <img src="../../uploads/<?php echo htmlspecialchars($report['submitter_image']); ?>" 
                                 alt="Profile" class="rounded-circle me-2" width="40" height="40">
                        <?php else: ?>
                            <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center me-2" 
                                 style="width: 40px; height: 40px;">
                                <i class="fas fa-user text-white"></i>
                            </div>
                        <?php endif; ?>
                        <div>
                            <div class="fw-bold"><?php echo htmlspecialchars($report['submitter_name']); ?></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Report Content -->
    <div class="mb-4">
        <h6><i class="fas fa-file-text text-primary me-1"></i> Report Content</h6>
        <div class="border rounded p-3 bg-light">
            <?php echo nl2br(htmlspecialchars($report['content'])); ?>
        </div>
    </div>

    <!-- File Attachment -->
    <?php if (!empty($report['file_path'])): ?>
    <div class="mb-4">
        <h6><i class="fas fa-paperclip text-primary me-1"></i> Attachment</h6>
        <div class="border rounded p-3 bg-light">
            <a href="../../uploads/reports/<?php echo htmlspecialchars($report['file_path']); ?>" 
               target="_blank" class="btn btn-outline-primary btn-sm">
                <i class="fas fa-download me-1"></i>
                Download: <?php echo htmlspecialchars($report['file_path']); ?>
            </a>
        </div>
    </div>
    <?php endif; ?>

    <!-- Responses Section -->
    <?php if ($responseTableExists): ?>
    <div class="mb-4">
        <h6><i class="fas fa-comments text-primary me-1"></i> Responses (<?php echo count($responses); ?>)</h6>
        
        <?php if (!empty($responses)): ?>
            <div class="responses-container" style="max-height: 300px; overflow-y: auto;">
                <?php foreach ($responses as $response): ?>
                <div class="border rounded p-3 mb-2 bg-light">
                    <div class="d-flex align-items-start">
                        <?php if (!empty($response['profile_image'])): ?>
                            <img src="../../uploads/<?php echo htmlspecialchars($response['profile_image']); ?>" 
                                 alt="Profile" class="rounded-circle me-2" width="32" height="32">
                        <?php else: ?>
                            <div class="bg-secondary rounded-circle d-flex align-items-center justify-content-center me-2" 
                                 style="width: 32px; height: 32px;">
                                <i class="fas fa-user text-white" style="font-size: 12px;"></i>
                            </div>
                        <?php endif; ?>
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between align-items-start mb-1">
                                <strong><?php echo htmlspecialchars($response['full_name']); ?></strong>
                                <small class="text-muted"><?php echo date('M j, Y g:i a', strtotime($response['created_at'])); ?></small>
                            </div>
                            <p class="mb-1"><?php echo nl2br(htmlspecialchars($response['response_text'])); ?></p>
                            <?php if (!empty($response['attachment_path'])): ?>
                                <div class="mt-2">
                                    <a href="../../uploads/reports/<?php echo htmlspecialchars($response['attachment_path']); ?>" 
                                       target="_blank" class="btn btn-outline-secondary btn-sm">
                                        <i class="fas fa-paperclip me-1"></i>
                                        <?php echo htmlspecialchars($response['attachment_path']); ?>
                                    </a>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="text-muted text-center py-3">
                <i class="fas fa-comment-slash fa-2x mb-2"></i>
                <p>No responses yet.</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Add Response Form -->
    <div class="border-top pt-3">
        <h6><i class="fas fa-reply text-primary me-1"></i> Add Response</h6>
        <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>
    <?php endif; ?>
</div>

<script>
console.log('Diocesan 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>
