<?php
/**
 * Reports Management
 * GHAMECC Choir Management Platform
 */

// Include necessary files
require_once '../includes/header.php';
require_once '../includes/auth.php';
require_once '../config/database.php';

// Require login
requireLogin();

// Set page title
$pageTitle = "Reports Management";

// Get user role and entity IDs
$userRole = $_SESSION['role'] ?? '';
$userSocietyId = $_SESSION['society_id'] ?? null;
$userCircuitId = $_SESSION['circuit_id'] ?? null;
$userDioceseId = $_SESSION['diocese_id'] ?? null;

// Initialize variables
$societies = [];
$reportTemplates = [];
$recentReports = [];
$message = '';
$error = '';

// Process form submission for generating a new report
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_report'])) {
    $reportType = $_POST['report_type'] ?? '';
    $societyId = $_POST['society_id'] ?? '';
    $startDate = $_POST['start_date'] ?? '';
    $endDate = $_POST['end_date'] ?? '';
    $reportTitle = $_POST['report_title'] ?? '';
    $description = $_POST['description'] ?? '';
    
    // Validate input
    if (empty($reportType) || empty($startDate) || empty($endDate) || empty($reportTitle)) {
        $error = "Please fill all required fields.";
    } else {
        // Generate report file name
        $reportFileName = 'report_' . time() . '_' . uniqid() . '.pdf';
        $reportPath = '../uploads/reports/' . $reportFileName;
        
        // Insert report record
        $query = "INSERT INTO reports (title, report_type, society_id, start_date, end_date, description, file_path, generated_by) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($query);
        $stmt->bind_param("ssissssi", $reportTitle, $reportType, $societyId, $startDate, $endDate, $description, $reportPath, $_SESSION['user_id']);
        
        if ($stmt->execute()) {
            $message = "Report request submitted successfully. The report will be generated shortly.";
        } else {
            $error = "Error submitting report request: " . $conn->error;
        }
        
        $stmt->close();
    }
}

// Get societies based on user role and access level
if ($userRole === 'admin') {
    // Admin can see all societies
    $query = "SELECT id, name FROM societies ORDER BY name";
    $stmt = $conn->prepare($query);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} elseif ($userRole === 'diocesan_secretary' && !empty($userDioceseId)) {
    // Diocese secretary can see societies in their diocese
    $query = "SELECT s.id, s.name 
              FROM societies s 
              JOIN circuits c ON s.circuit_id = c.id 
              WHERE c.diocese_id = ? 
              ORDER BY s.name";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userDioceseId);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} elseif ($userRole === 'circuit_secretary' && !empty($userCircuitId)) {
    // Circuit secretary can see societies in their circuit
    $query = "SELECT id, name FROM societies WHERE circuit_id = ? ORDER BY name";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userCircuitId);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} elseif (!empty($userSocietyId)) {
    // Society users can only see their own society
    $query = "SELECT id, name FROM societies WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userSocietyId);
    $stmt->execute();
    $result = $stmt->get_result();
    $societies = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
}

// Get report templates
$query = "SELECT id, name, description, report_type FROM report_templates ORDER BY name";
$stmt = $conn->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
$reportTemplates = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Get recent reports
$query = "SELECT r.id, r.title, r.report_type, r.generated_date, r.file_path, 
          r.status, s.name as society_name, u.full_name as generated_by
          FROM reports r
          LEFT JOIN societies s ON r.society_id = s.id
          LEFT JOIN users u ON r.generated_by = u.id";

// Add filters based on user role
$whereParams = [];
if ($userRole === 'admin') {
    // No additional filters for admin
} elseif ($userRole === 'diocesan_secretary' && !empty($userDioceseId)) {
    $query .= " JOIN circuits c ON s.circuit_id = c.id WHERE c.diocese_id = ?";
    $whereParams[] = $userDioceseId;
} elseif ($userRole === 'circuit_secretary' && !empty($userCircuitId)) {
    $query .= " WHERE s.circuit_id = ?";
    $whereParams[] = $userCircuitId;
} elseif (!empty($userSocietyId)) {
    $query .= " WHERE r.society_id = ?";
    $whereParams[] = $userSocietyId;
}

$query .= " ORDER BY r.generated_date DESC LIMIT 10";

$stmt = $conn->prepare($query);

// Bind parameters if any
if (!empty($whereParams)) {
    $types = str_repeat("i", count($whereParams));
    $stmt->bind_param($types, ...$whereParams);
}

$stmt->execute();
$result = $stmt->get_result();
$recentReports = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// Close connection
$conn->close();
?>

<!-- Begin Page Content -->
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>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>
<div class="container-fluid">
    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800"><?php echo $pageTitle; ?></h1>
    </div>

    <?php if (!empty($message)): ?>
        <div class="alert alert-success" role="alert">
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if (!empty($error)): ?>
        <div class="alert alert-danger" role="alert">
            <?php echo $error; ?>
        </div>
    <?php endif; ?>

    <!-- Content Row -->
    <div class="row">
        <!-- Generate Report Card -->
        <div class="col-xl-6 col-md-12 mb-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Generate New Report</h6>
                </div>
                <div class="card-body">
                    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
                        <div class="mb-3">
                            <label for="report_title" class="form-label">Report Title</label>
                            <input type="text" class="form-control" id="report_title" name="report_title" required>
                        </div>

                        <div class="mb-3">
                            <label for="report_type" class="form-label">Report Type</label>
                            <select class="form-select" id="report_type" name="report_type" required>
                                <option value="">Select Report Type</option>
                                <option value="attendance">Attendance Report</option>
                                <option value="financial">Financial Report</option>
                                <option value="membership">Membership Report</option>
                                <option value="activity">Activity Report</option>
                                <option value="custom">Custom Report</option>
                            </select>
                        </div>

                        <div class="mb-3">
                            <label for="society_id" class="form-label">Society</label>
                            <select class="form-select" id="society_id" name="society_id">
                                <option value="">All Societies</option>
                                <?php foreach ($societies as $society): ?>
                                    <option value="<?php echo $society['id']; ?>">
                                        <?php echo htmlspecialchars($society['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="start_date" class="form-label">Start Date</label>
                                <input type="date" class="form-control" id="start_date" name="start_date" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="end_date" class="form-label">End Date</label>
                                <input type="date" class="form-control" id="end_date" name="end_date" 
                                       value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="description" class="form-label">Description</label>
                            <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                        </div>

                        <div class="d-grid gap-2">
                            <button type="submit" name="generate_report" class="btn btn-primary">Generate Report</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Report Templates Card -->
        <div class="col-xl-6 col-md-12 mb-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Available Report Templates</h6>
                </div>
                <div class="card-body">
                    <?php if (empty($reportTemplates)): ?>
                        <p>No report templates available.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-bordered" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>Template Name</th>
                                        <th>Type</th>
                                        <th>Description</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($reportTemplates as $template): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($template['name']); ?></td>
                                            <td><?php echo ucfirst(htmlspecialchars($template['report_type'])); ?></td>
                                            <td><?php echo htmlspecialchars($template['description']); ?></td>
                                            <td>
                                                <a href="use_template.php?id=<?php echo $template['id']; ?>" class="btn btn-sm btn-primary">
                                                    <i class="fas fa-file-alt"></i> Use
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Reports Row -->
    <div class="row">
        <div class="col-xl-12 col-lg-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Recent Reports</h6>
                </div>
                <div class="card-body">
                    <?php if (empty($recentReports)): ?>
                        <p>No reports found.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-bordered" width="100%" cellspacing="0">
                                <thead>
                                    <tr>
                                        <th>Title</th>
                                        <th>Type</th>
                                        <th>Society</th>
                                        <th>Generated By</th>
                                        <th>Date</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recentReports as $report): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($report['title']); ?></td>
                                            <td><?php echo ucfirst(htmlspecialchars($report['report_type'])); ?></td>
                                            <td><?php echo htmlspecialchars($report['society_name'] ?? 'All Societies'); ?></td>
                                            <td><?php echo htmlspecialchars($report['generated_by']); ?></td>
                                            <td><?php echo date('d M Y', strtotime($report['generated_date'])); ?></td>
                                            <td>
                                                <?php if ($report['status'] === 'completed'): ?>
                                                    <span class="badge bg-success">Completed</span>
                                                <?php elseif ($report['status'] === 'processing'): ?>
                                                    <span class="badge bg-warning">Processing</span>
                                                <?php elseif ($report['status'] === 'failed'): ?>
                                                    <span class="badge bg-danger">Failed</span>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">Pending</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($report['status'] === 'completed'): ?>
                                                    <a href="../uploads/reports/<?php echo $report['file_path']; ?>" class="btn btn-sm btn-success" target="_blank">
                                                        <i class="fas fa-download"></i> Download
                                                    </a>
                                                <?php else: ?>
                                                    <button class="btn btn-sm btn-secondary" disabled>
                                                        <i class="fas fa-clock"></i> Pending
                                                    </button>
                                                <?php endif; ?>
                                                <a href="view.php?id=<?php echo $report['id']; ?>" class="btn btn-sm btn-info">
                                                    <i class="fas fa-eye"></i> Details
                                                </a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="mt-3">
                            <a href="all_reports.php" class="btn btn-info btn-sm">View All Reports</a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Report Statistics Row -->
    <div class="row">
        <!-- Reports by Type Chart -->
        <div class="col-xl-6 col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Reports by Type</h6>
                </div>
                <div class="card-body">
                    <div class="chart-pie">
                        <canvas id="reportsByTypeChart"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- Reports by Month Chart -->
        <div class="col-xl-6 col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">Reports Generated by Month</h6>
                </div>
                <div class="card-body">
                    <div class="chart-bar">
                        <canvas id="reportsByMonthChart"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- End of Page Content -->

<!-- JavaScript for charts -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Reports by Type Chart
    const reportsByTypeCtx = document.getElementById('reportsByTypeChart');
    
    // Sample data - in a real application, this would be loaded from the server
    const reportsByTypeData = {
        labels: ['Attendance', 'Financial', 'Membership', 'Activity', 'Custom'],
        datasets: [{
            data: [30, 25, 20, 15, 10],
            backgroundColor: [
                'rgba(78, 115, 223, 0.8)',
                'rgba(54, 185, 204, 0.8)',
                'rgba(246, 194, 62, 0.8)',
                'rgba(28, 200, 138, 0.8)',
                'rgba(231, 74, 59, 0.8)'
            ],
            borderWidth: 1
        }]
    };
    
    new Chart(reportsByTypeCtx, {
        type: 'pie',
        data: reportsByTypeData,
        options: {
            maintainAspectRatio: false
        }
    });
    
    // Reports by Month Chart
    const reportsByMonthCtx = document.getElementById('reportsByMonthChart');
    
    // Sample data - in a real application, this would be loaded from the server
    const reportsByMonthData = {
        labels: ['January', 'February', 'March', 'April', 'May', 'June'],
        datasets: [{
            label: 'Reports Generated',
            backgroundColor: 'rgba(78, 115, 223, 0.5)',
            borderColor: 'rgba(78, 115, 223, 1)',
            data: [12, 19, 15, 8, 22, 14],
        }]
    };
    
    new Chart(reportsByMonthCtx, {
        type: 'bar',
        data: reportsByMonthData,
        options: {
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
});
</script>

<?php
// Include footer
require_once '../includes/footer.php';
?>
