<?php
/**
 * Sent Reports Page
 * 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
$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]);

// Get all reports submitted by this user
$reports = fetchRows("SELECT r.*, 
                     CASE 
                        WHEN r.target_type = 'society' THEN (SELECT name FROM societies WHERE id = r.target_id)
                        WHEN r.target_type = 'circuit' THEN (SELECT name FROM circuits WHERE id = r.target_id)
                        WHEN r.target_type = 'diocese' THEN (SELECT name FROM dioceses WHERE id = r.target_id)
                        WHEN r.target_type = 'connexional' THEN 'Connexional Office'
                        ELSE 'Unknown'
                     END as target_name
                     FROM reports r
                     WHERE r.submitted_by = ?
                     ORDER BY r.created_at DESC", [$userId]);

// Set base path for includes
$basePath = '..';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sent Reports - GHAMECC Choir Management</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables CSS -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <!-- Custom CSS -->
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <?php include '../includes/navbar.php'; ?>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include '../includes/sidebar.php'; ?>
            
            <!-- Main Content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4 py-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Sent Reports</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="submit.php" class="btn btn-sm btn-outline-primary me-2">
                            <i class="fas fa-plus me-1"></i> Submit New Report
                        </a>
                        <a href="received.php" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-inbox me-1"></i> View Received Reports
                        </a>
                    </div>
                </div>
                
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Your Submitted Reports</h6>
                    </div>
                    <div class="card-body">
                        <?php if (empty($reports)): ?>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                You haven't submitted any reports yet.
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-bordered" id="sentReportsTable" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Date</th>
                                            <th>To</th>
                                            <th>Type</th>
                                            <th>Subject</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($reports as $report): ?>
                                            <tr>
                                                <td><?php echo $report['id']; ?></td>
                                                <td><?php echo date('M d, Y', strtotime($report['created_at'])); ?></td>
                                                <td>
                                                    <?php echo htmlspecialchars($report['target_name']); ?>
                                                    <div class="small text-muted"><?php echo ucfirst($report['target_type']); ?></div>
                                                </td>
                                                <td>
                                                    <?php 
                                                    $reportTypeLabels = [
                                                        'monthly_activity' => 'Monthly Activity',
                                                        'quarterly_report' => 'Quarterly Report',
                                                        'annual_report' => 'Annual Report',
                                                        'financial_report' => 'Financial Report',
                                                        'secretariate_report' => 'Secretariate Report',
                                                        'music_directorate_report' => 'Music Directorate',
                                                        'conference_report' => 'Conference Report',
                                                        'administrative' => 'Administrative',
                                                        'system_update' => 'System Update',
                                                        'policy_update' => 'Policy Update',
                                                        'announcement' => 'Announcement',
                                                        'special_notice' => 'Special Notice',
                                                        'special_request' => 'Special Request'
                                                    ];
                                                    
                                                    // Get report type from report_type_id
                                                    $reportTypeName = '';
                                                    $reportTypeQuery = "SELECT name FROM report_types WHERE id = ?";
                                                    $reportTypeResult = fetchRow($reportTypeQuery, [$report['report_type_id'] ?? 0]);
                                                    if ($reportTypeResult) {
                                                        $reportTypeName = $reportTypeResult['name'];
                                                    }
                                                    
                                                    echo htmlspecialchars($reportTypeName);
                                                    ?>
                                                </td>
                                                <td><?php echo htmlspecialchars($report['title'] ?? ''); ?></td>
                                                <td>
                                                    <?php if ($report['status'] === 'pending'): ?>
                                                        <span class="badge bg-warning">Pending</span>
                                                    <?php elseif ($report['status'] === 'approved'): ?>
                                                        <span class="badge bg-success">Approved</span>
                                                    <?php elseif ($report['status'] === 'rejected'): ?>
                                                        <span class="badge bg-danger">Rejected</span>
                                                    <?php elseif ($report['status'] === 'completed'): ?>
                                                        <span class="badge bg-info">Completed</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-primary view-report" data-bs-toggle="modal" data-bs-target="#viewReportModal" data-report-id="<?php echo $report['id']; ?>">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </main>
        </div>
    </div>
    
    <!-- View Report Modal -->
    <div class="modal fade" id="viewReportModal" tabindex="-1" aria-labelledby="viewReportModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewReportModalLabel">View Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="reportDetails">
                        <div class="text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Loading...</span>
                            </div>
                            <p>Loading report details...</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Bootstrap JS Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <!-- Custom JS -->
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#sentReportsTable').DataTable({
                order: [[0, 'desc']]
            });
            
            // Handle view report button
            $('.view-report').on('click', function() {
                const reportId = $(this).data('report-id');
                $('#reportDetails').html('<div class="text-center"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p>Loading report details...</p></div>');
                
                // Fetch report details via AJAX
                $.ajax({
                    url: 'ajax/get_report_details.php',
                    type: 'GET',
                    data: { report_id: reportId },
                    success: function(response) {
                        $('#reportDetails').html(response);
                    },
                    error: function() {
                        $('#reportDetails').html('<div class="alert alert-danger">Failed to load report details. Please try again.</div>');
                    }
                });
            });
        });
    </script>
</body>
</html>
