<?php
/**
 * Circuit Report Consolidation Page
 * GHAMECC Choir Management Platform
 * 
 * Allows circuit-level users to consolidate reports from societies under their circuit
 * by report type, creating unified circuit reports with update/edit functionality
 */

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

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

// Include logger
require_once '../config/logger.php';

// Require login
requireLogin();

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

// Check if user has circuit-level permissions
if (!in_array($userInfo['role_key'] ?? '', ['circuit_chairman', 'circuit_secretary', 'circuit_dom', 'circuit_treasurer'])) {
    header('Location: ../dashboard.php');
    exit();
}

// Get user's circuit information
$circuitId = $_SESSION['circuit_id'] ?? $userInfo['circuit_id'] ?? null;
if (!$circuitId) {
    // Try to get circuit from member association
    $memberQuery = "SELECT m.circuit_id FROM users u JOIN members m ON u.member_id = m.id WHERE u.id = ?";
    $memberInfo = fetchRow($memberQuery, [$userId]);
    $circuitId = $memberInfo['circuit_id'] ?? null;
}

if (!$circuitId) {
    die("Circuit information not found. Please contact administrator.");
}

// Get circuit details
$circuit = fetchRow("SELECT c.*, d.name as diocese_name, d.id as diocese_id 
                    FROM circuits c 
                    JOIN dioceses d ON c.diocese_id = d.id 
                    WHERE c.id = ?", [$circuitId]);

// Get societies in this circuit
$societies = fetchRows("SELECT * FROM societies WHERE circuit_id = ? ORDER BY name", [$circuitId]);

// Get report types
$reportTypes = fetchRows("SELECT * FROM report_types ORDER BY category, name");

// Process consolidation request
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'consolidate') {
        $reportTypeId = (int)$_POST['report_type_id'];
        $consolidatedTitle = escapeString($_POST['consolidated_title']);
        $consolidatedContent = escapeString($_POST['consolidated_content']);
        $selectedReports = $_POST['selected_reports'] ?? [];
        
        if (empty($selectedReports)) {
            $message = "Please select at least one report to consolidate.";
            $messageType = "warning";
        } else {
            // Create consolidated circuit report
            $insertSql = "INSERT INTO reports (title, content, report_type_id, source_type, source_id, 
                         target_type, target_id, submitted_by, status, created_at) 
                         VALUES (?, ?, ?, 'circuit', ?, 'diocese', ?, ?, 'pending', NOW())";
            
            if (executeQuery($insertSql, [$consolidatedTitle, $consolidatedContent, $reportTypeId, 
                           $circuitId, $circuit['diocese_id'], $userId])) {
                
                $consolidatedReportId = $conn->insert_id;
                
                // Update source reports to mark them as consolidated
                foreach ($selectedReports as $reportId) {
                    executeQuery("UPDATE reports SET consolidated_into = ?, status = 'consolidated' WHERE id = ?", 
                               [$consolidatedReportId, (int)$reportId]);
                }
                
                $message = "Reports consolidated successfully into circuit report.";
                $messageType = "success";
                
                logInfo("Circuit reports consolidated", [
                    'user_id' => $userId,
                    'circuit_id' => $circuitId,
                    'consolidated_report_id' => $consolidatedReportId,
                    'source_reports' => $selectedReports
                ]);
            } else {
                $message = "Failed to create consolidated report. Please try again.";
                $messageType = "danger";
            }
        }
    } elseif ($action === 'update_consolidated') {
        $reportId = (int)$_POST['report_id'];
        $title = escapeString($_POST['title']);
        $content = escapeString($_POST['content']);
        
        // Verify this is a circuit report that belongs to this user's circuit
        $report = fetchRow("SELECT * FROM reports WHERE id = ? AND source_type = 'circuit' AND source_id = ?", 
                          [$reportId, $circuitId]);
        
        if ($report) {
            if (executeQuery("UPDATE reports SET title = ?, content = ?, updated_at = NOW() WHERE id = ?", 
                           [$title, $content, $reportId])) {
                $message = "Consolidated report updated successfully.";
                $messageType = "success";
            } else {
                $message = "Failed to update report. Please try again.";
                $messageType = "danger";
            }
        } else {
            $message = "Invalid report or insufficient permissions.";
            $messageType = "danger";
        }
    }
}

// Get society reports available for consolidation (approved reports not yet consolidated)
$availableReports = [];
if (isset($_GET['report_type_id'])) {
    $reportTypeId = (int)$_GET['report_type_id'];
    $availableReports = fetchRows("
        SELECT r.*, s.name as society_name, u.full_name as submitted_by_name,
               rt.name as report_type_name
        FROM reports r
        JOIN societies s ON r.source_id = s.id AND r.source_type = 'society'
        JOIN users u ON r.submitted_by = u.id
        JOIN report_types rt ON r.report_type_id = rt.id
        WHERE s.circuit_id = ? 
        AND r.report_type_id = ? 
        AND r.target_type = 'circuit' 
        AND r.target_id = ?
        AND r.status = 'approved'
        AND (r.consolidated_into IS NULL OR r.consolidated_into = 0)
        ORDER BY r.created_at DESC
    ", [$circuitId, $reportTypeId, $circuitId]);
}

// Get existing consolidated reports for this circuit
$consolidatedReports = fetchRows("
    SELECT r.*, rt.name as report_type_name, rt.category,
           COUNT(source_reports.id) as source_count
    FROM reports r
    JOIN report_types rt ON r.report_type_id = rt.id
    LEFT JOIN reports source_reports ON source_reports.consolidated_into = r.id
    WHERE r.source_type = 'circuit' 
    AND r.source_id = ?
    GROUP BY r.id
    ORDER BY r.created_at DESC
", [$circuitId]);

// 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>Circuit Report Consolidation - 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">Circuit Report Consolidation</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="received.php" class="btn btn-sm btn-outline-secondary me-2">
                            <i class="fas fa-arrow-left me-1"></i> Back to Reports
                        </a>
                    </div>
                </div>
                
                <!-- Circuit Information -->
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">
                            <i class="fas fa-network-wired me-2"></i>
                            <?php echo htmlspecialchars($circuit['name']); ?> Circuit
                        </h6>
                    </div>
                    <div class="card-body">
                        <p class="mb-1"><strong>Diocese:</strong> <?php echo htmlspecialchars($circuit['diocese_name']); ?></p>
                        <p class="mb-0"><strong>Societies:</strong> <?php echo count($societies); ?> societies under this circuit</p>
                    </div>
                </div>
                
                <!-- Alert Messages -->
                <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                        <?php echo $message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <!-- Consolidation Interface -->
                <div class="row">
                    <!-- Report Type Selection -->
                    <div class="col-md-4">
                        <div class="card shadow mb-4">
                            <div class="card-header py-3">
                                <h6 class="m-0 font-weight-bold text-primary">Select Report Type</h6>
                            </div>
                            <div class="card-body">
                                <form method="get" action="">
                                    <div class="mb-3">
                                        <label for="report_type_id" class="form-label">Report Type</label>
                                        <select class="form-select" id="report_type_id" name="report_type_id" onchange="this.form.submit()">
                                            <option value="">Choose report type...</option>
                                            <?php 
                                            $currentCategory = '';
                                            foreach ($reportTypes as $type): 
                                                if ($type['category'] !== $currentCategory):
                                                    if ($currentCategory !== '') echo '</optgroup>';
                                                    echo '<optgroup label="' . htmlspecialchars($type['category']) . '">';
                                                    $currentCategory = $type['category'];
                                                endif;
                                            ?>
                                                <option value="<?php echo $type['id']; ?>" 
                                                        <?php echo (isset($_GET['report_type_id']) && $_GET['report_type_id'] == $type['id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($type['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                            <?php if ($currentCategory !== '') echo '</optgroup>'; ?>
                                        </select>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Available Reports for Consolidation -->
                    <div class="col-md-8">
                        <?php if (!empty($availableReports)): ?>
                            <div class="card shadow mb-4">
                                <div class="card-header py-3">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        Available Reports for Consolidation
                                        <span class="badge bg-info ms-2"><?php echo count($availableReports); ?></span>
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <form method="post" action="">
                                        <input type="hidden" name="action" value="consolidate">
                                        <input type="hidden" name="report_type_id" value="<?php echo $_GET['report_type_id']; ?>">
                                        
                                        <div class="mb-3">
                                            <label for="consolidated_title" class="form-label">Consolidated Report Title</label>
                                            <input type="text" class="form-control" id="consolidated_title" name="consolidated_title" 
                                                   value="<?php echo htmlspecialchars($circuit['name']); ?> Circuit - <?php echo htmlspecialchars($availableReports[0]['report_type_name'] ?? ''); ?> - <?php echo date('M Y'); ?>" required>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Select Reports to Consolidate</label>
                                            <div class="table-responsive">
                                                <table class="table table-sm">
                                                    <thead>
                                                        <tr>
                                                            <th width="50">
                                                                <input type="checkbox" id="selectAll" class="form-check-input">
                                                            </th>
                                                            <th>Society</th>
                                                            <th>Title</th>
                                                            <th>Date</th>
                                                            <th>Submitted By</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($availableReports as $report): ?>
                                                            <tr>
                                                                <td>
                                                                    <input type="checkbox" name="selected_reports[]" 
                                                                           value="<?php echo $report['id']; ?>" 
                                                                           class="form-check-input report-checkbox">
                                                                </td>
                                                                <td><?php echo htmlspecialchars($report['society_name']); ?></td>
                                                                <td><?php echo htmlspecialchars($report['title']); ?></td>
                                                                <td><?php echo date('M d, Y', strtotime($report['created_at'])); ?></td>
                                                                <td><?php echo htmlspecialchars($report['submitted_by_name']); ?></td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="consolidated_content" class="form-label">Consolidated Content</label>
                                            <textarea class="form-control" id="consolidated_content" name="consolidated_content" 
                                                      rows="8" placeholder="Enter the consolidated report content here..."></textarea>
                                            <div class="form-text">
                                                <button type="button" class="btn btn-sm btn-outline-info" onclick="autoGenerateContent()">
                                                    <i class="fas fa-magic me-1"></i> Auto-Generate from Selected Reports
                                                </button>
                                            </div>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="fas fa-compress-alt me-1"></i> Create Consolidated Report
                                        </button>
                                    </form>
                                </div>
                            </div>
                        <?php elseif (isset($_GET['report_type_id'])): ?>
                            <div class="card shadow mb-4">
                                <div class="card-body text-center">
                                    <i class="fas fa-info-circle text-info fa-3x mb-3"></i>
                                    <h5>No Reports Available</h5>
                                    <p class="text-muted">No approved reports of this type are available for consolidation from societies in your circuit.</p>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Existing Consolidated Reports -->
                <?php if (!empty($consolidatedReports)): ?>
                    <div class="card shadow mb-4">
                        <div class="card-header py-3">
                            <h6 class="m-0 font-weight-bold text-primary">Existing Consolidated Reports</h6>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered" id="consolidatedReportsTable">
                                    <thead>
                                        <tr>
                                            <th>Title</th>
                                            <th>Type</th>
                                            <th>Source Reports</th>
                                            <th>Status</th>
                                            <th>Created</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($consolidatedReports as $report): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($report['title']); ?></td>
                                                <td>
                                                    <span class="badge bg-secondary"><?php echo htmlspecialchars($report['category']); ?></span>
                                                    <?php echo htmlspecialchars($report['report_type_name']); ?>
                                                </td>
                                                <td>
                                                    <span class="badge bg-info"><?php echo $report['source_count']; ?> reports</span>
                                                </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 endif; ?>
                                                </td>
                                                <td><?php echo date('M d, Y', strtotime($report['created_at'])); ?></td>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-primary view-consolidated" 
                                                            data-bs-toggle="modal" data-bs-target="#viewConsolidatedModal" 
                                                            data-report-id="<?php echo $report['id']; ?>">
                                                        <i class="fas fa-eye"></i>
                                                    </button>
                                                    <?php if ($report['status'] === 'pending'): ?>
                                                        <button type="button" class="btn btn-sm btn-warning edit-consolidated" 
                                                                data-bs-toggle="modal" data-bs-target="#editConsolidatedModal" 
                                                                data-report-id="<?php echo $report['id']; ?>"
                                                                data-title="<?php echo htmlspecialchars($report['title']); ?>"
                                                                data-content="<?php echo htmlspecialchars($report['content']); ?>">
                                                            <i class="fas fa-edit"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
    
    <!-- View Consolidated Report Modal -->
    <div class="modal fade" id="viewConsolidatedModal" tabindex="-1" aria-labelledby="viewConsolidatedModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="viewConsolidatedModalLabel">View Consolidated Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="consolidatedReportDetails">
                        <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>
    
    <!-- Edit Consolidated Report Modal -->
    <div class="modal fade" id="editConsolidatedModal" tabindex="-1" aria-labelledby="editConsolidatedModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editConsolidatedModalLabel">Edit Consolidated Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="post" action="">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="update_consolidated">
                        <input type="hidden" name="report_id" id="editReportId">
                        
                        <div class="mb-3">
                            <label for="editTitle" class="form-label">Title</label>
                            <input type="text" class="form-control" id="editTitle" name="title" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="editContent" class="form-label">Content</label>
                            <textarea class="form-control" id="editContent" name="content" rows="10" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Update Report</button>
                    </div>
                </form>
            </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>
    
    <script>
        $(document).ready(function() {
            // Initialize DataTable
            $('#consolidatedReportsTable').DataTable({
                order: [[4, 'desc']]
            });
            
            // Select all checkbox functionality
            $('#selectAll').on('change', function() {
                $('.report-checkbox').prop('checked', this.checked);
            });
            
            // Update select all when individual checkboxes change
            $('.report-checkbox').on('change', function() {
                const totalCheckboxes = $('.report-checkbox').length;
                const checkedCheckboxes = $('.report-checkbox:checked').length;
                $('#selectAll').prop('checked', totalCheckboxes === checkedCheckboxes);
            });
            
            // View consolidated report
            $('.view-consolidated').on('click', function() {
                const reportId = $(this).data('report-id');
                $('#consolidatedReportDetails').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>');
                
                $.ajax({
                    url: 'ajax/get_report_details.php',
                    type: 'GET',
                    data: { report_id: reportId },
                    success: function(response) {
                        $('#consolidatedReportDetails').html(response);
                    },
                    error: function() {
                        $('#consolidatedReportDetails').html('<div class="alert alert-danger">Failed to load report details. Please try again.</div>');
                    }
                });
            });
            
            // Edit consolidated report
            $('.edit-consolidated').on('click', function() {
                $('#editReportId').val($(this).data('report-id'));
                $('#editTitle').val($(this).data('title'));
                $('#editContent').val($(this).data('content'));
            });
        });
        
        // Auto-generate consolidated content from selected reports
        function autoGenerateContent() {
            const selectedReports = $('.report-checkbox:checked');
            if (selectedReports.length === 0) {
                alert('Please select reports first.');
                return;
            }
            
            let content = 'CONSOLIDATED CIRCUIT REPORT\n';
            content += '============================\n\n';
            content += 'This report consolidates the following society reports:\n\n';
            
            selectedReports.each(function(index) {
                const row = $(this).closest('tr');
                const society = row.find('td:eq(1)').text();
                const title = row.find('td:eq(2)').text();
                const date = row.find('td:eq(3)').text();
                
                content += `${index + 1}. ${society} - ${title} (${date})\n`;
            });
            
            content += '\n\nCONSOLIDATED SUMMARY:\n';
            content += '====================\n\n';
            content += '[Please provide a summary of the key points from the selected reports]\n\n';
            content += 'KEY HIGHLIGHTS:\n';
            content += '- [Add key highlight 1]\n';
            content += '- [Add key highlight 2]\n';
            content += '- [Add key highlight 3]\n\n';
            content += 'RECOMMENDATIONS:\n';
            content += '- [Add recommendation 1]\n';
            content += '- [Add recommendation 2]\n\n';
            content += 'CIRCUIT SECRETARY NOTES:\n';
            content += '[Add any additional circuit-level observations or comments]\n';
            
            $('#consolidated_content').val(content);
        }
    </script>
</body>
</html>
