<?php
require_once '../../config/config.php';

try {
    // Get filter parameters
    $examDate = isset($_GET['exam_date']) ? trim($_GET['exam_date']) : '';
    $session = isset($_GET['session']) ? trim($_GET['session']) : '';
    $staffId = isset($_GET['staff_id']) ? (int)$_GET['staff_id'] : 0;
    $status = isset($_GET['status']) ? trim($_GET['status']) : '';

    // Build WHERE clause
    $where = [];
    $bindings = [];

    // Add filter conditions
    if ($examDate !== '') {
        $where[] = 's.exam_date = ?';
        $bindings[] = $examDate;
    }

    if ($session !== '') {
        $where[] = 's.session = ?';
        $bindings[] = $session;
    }

    if ($staffId > 0) {
        $where[] = 's.staff_id = ?';
        $bindings[] = $staffId;
    }

    if ($status !== '') {
        $where[] = 's.status = ?';
        $bindings[] = $status;
    }

    $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

    // Get squad data
    $sql = "SELECT 
                s.squad_id,
                s.squad_name,
                s.exam_date,
                s.session,
                s.staff_id,
                s.status,
                s.created_at,
                st.first_name,
                st.last_name,
                st.staff_code
            FROM squads s
            LEFT JOIN staff st ON s.staff_id = st.staff_id
            $whereClause
            ORDER BY s.exam_date DESC, s.session, s.squad_name, st.first_name";

    $stmt = $pdo->prepare($sql);
    foreach ($bindings as $index => $value) {
        $stmt->bindValue($index + 1, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
    }
    $stmt->execute();
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Debug information
    if (isset($_GET['debug']) && $_GET['debug'] === '1') {
        echo "<h3>Debug Information:</h3>";
        echo "<p><strong>SQL Query:</strong> " . $sql . "</p>";
        echo "<p><strong>Bindings:</strong> " . print_r($bindings, true) . "</p>";
        echo "<p><strong>Data Count:</strong> " . count($data) . "</p>";
        echo "<p><strong>Data:</strong></p>";
        echo "<pre>" . print_r($data, true) . "</pre>";
        exit;
    }

    // Get college information for header
    $collegeInfo = null;
    if (!empty($data)) {
        $collegeSql = "SELECT DISTINCT col.college_id, col.college_name, col.college_code, 
                              col.address, col.location, col.logo, col.seal
                       FROM squads s
                       LEFT JOIN staff st ON s.staff_id = st.staff_id
                       LEFT JOIN colleges col ON st.college_id = col.college_id
                       $whereClause
                       LIMIT 1";

        $stmtCollege = $pdo->prepare($collegeSql);
        foreach ($bindings as $index => $value) {
            $stmtCollege->bindValue($index + 1, $value, is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR);
        }
        $stmtCollege->execute();
        $collegeData = $stmtCollege->fetch(PDO::FETCH_ASSOC);
        
        if ($collegeData) {
            $collegeInfo = [
                'college_id' => $collegeData['college_id'],
                'college_name' => $collegeData['college_name'],
                'college_code' => $collegeData['college_code'],
                'address' => $collegeData['address'],
                'location' => $collegeData['location'],
                'logo' => $collegeData['logo'],
                'seal' => $collegeData['seal']
            ];
        }
    }

    // Generate HTML report
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Squad Report</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 0;
                padding: 15px;
                background-color: white;
                font-size: 12px;
            }
            .report-container {
                max-width: 1200px;
                margin: 0 auto;
                background-color: white;
            }
            .header {
                text-align: center;
                margin-bottom: 20px;
                border-bottom: 2px solid #000;
                padding-bottom: 15px;
            }
            .header-top {
                display: flex;
                justify-content: center;
                align-items: flex-start;
                margin-bottom: 10px;
            }
            .college-logo {
                width: 80px;
                height: 80px;
                object-fit: contain;
                margin-right: 20px;
            }
            .header-center {
                flex: 1;
                text-align: center;
            }
            .proforma {
                font-size: 16px;
                font-weight: bold;
                margin-bottom: 10px;
                text-decoration: underline;
            }
            .college-info {
                margin-bottom: 10px;
            }
            .college-name {
                font-size: 18px;
                font-weight: bold;
                color: #000;
                margin-bottom: 5px;
            }
            .college-address {
                font-size: 12px;
                color: #333;
                margin-bottom: 3px;
            }
            .college-location {
                font-size: 12px;
                color: #333;
            }
            .report-title {
                font-size: 14px;
                font-weight: bold;
                margin-bottom: 10px;
                text-decoration: underline;
            }
            .exam-details {
                font-size: 12px;
                margin-bottom: 10px;
            }
            .squad-table {
                width: 100%;
                border-collapse: collapse;
                margin-bottom: 20px;
                border: 2px solid #000;
            }
            .squad-table th,
            .squad-table td {
                border: 1px solid #000;
                padding: 8px;
                text-align: center;
                font-size: 12px;
                vertical-align: middle;
            }
            .squad-table th {
                background-color: #f0f0f0;
                font-weight: bold;
                font-size: 13px;
            }
            .date-session-header {
                writing-mode: vertical-rl;
                text-orientation: mixed;
                width: 80px;
                padding: 20px 5px;
            }
            .squad-name-header {
                width: 150px;
            }
            .staff-header {
                width: 150px;
            }
            .status-header {
                width: 100px;
            }
            .status-badge {
                padding: 2px 6px;
                border-radius: 3px;
                font-size: 11px;
                font-weight: bold;
            }
            .status-active {
                background-color: #28a745;
                color: white;
            }
            .status-inactive {
                background-color: #dc3545;
                color: white;
            }
            .session-badge {
                padding: 2px 6px;
                border-radius: 3px;
                font-size: 11px;
                font-weight: bold;
            }
            .session-fn {
                background-color: #007bff;
                color: white;
            }
            .session-an {
                background-color: #ffc107;
                color: black;
            }
            .footer {
                margin-top: 30px;
                display: flex;
                justify-content: space-between;
                align-items: flex-end;
            }
            .footer-left {
                text-align: left;
            }
            .footer-right {
                text-align: right;
            }
            .signature-line {
                border-bottom: 1px solid #000;
                width: 200px;
                margin-top: 5px;
            }
            .summary-section {
                margin-bottom: 20px;
                padding: 10px;
                background-color: #f8f9fa;
                border: 1px solid #dee2e6;
                border-radius: 5px;
            }
            .summary-title {
                font-weight: bold;
                margin-bottom: 10px;
                font-size: 14px;
            }
            .summary-stats {
                display: flex;
                justify-content: space-around;
                flex-wrap: wrap;
            }
            .stat-item {
                text-align: center;
                margin: 5px;
            }
            .stat-number {
                font-size: 18px;
                font-weight: bold;
                color: #007bff;
            }
            .stat-label {
                font-size: 11px;
                color: #666;
            }
            @media print {
                body {
                    background-color: white;
                    padding: 10px;
                    margin: 0;
                }
                .report-container {
                    max-width: none;
                }
            }
        </style>
    </head>
    <body>
        <div class="report-container">
            <!-- Header -->
            <div class="header">
                <div class="header-top">
                    <div class="college-logo-section">
                        <?php if ($collegeInfo && $collegeInfo['logo']): ?>
                            <img src="../../data/college/<?php echo htmlspecialchars($collegeInfo['logo']); ?>" alt="College Logo" class="college-logo" onerror="this.style.display='none';">
                        <?php else: ?>
                            <div class="college-logo" style="display: flex; align-items: center; justify-content: center; color: #999; font-size: 10px;">LOGO</div>
                        <?php endif; ?>
                    </div>
                    <div class="header-center">
                        <div class="proforma">SQUAD REPORT</div>
                        <?php if ($collegeInfo): ?>
                            <div class="college-info">
                                <div class="college-name"><?php echo htmlspecialchars($collegeInfo['college_name']); ?></div>
                                <?php if ($collegeInfo['address']): ?>
                                    <div class="college-address"><?php echo htmlspecialchars($collegeInfo['address']); ?></div>
                                <?php endif; ?>
                                <?php if ($collegeInfo['location']): ?>
                                    <div class="college-location"><?php echo htmlspecialchars($collegeInfo['location']); ?></div>
                                <?php endif; ?>
                            </div>
                        <?php else: ?>
                            <div class="college-name">ANNA UNIVERSITY, CHENNAI - 25</div>
                        <?php endif; ?>
                        <div class="report-title">Squad Members Assignment Report</div>
                        <?php if ($collegeInfo): ?>
                            <div class="exam-details">
                                <strong>Centre: <?php echo htmlspecialchars($collegeInfo['college_code']); ?>-<?php echo htmlspecialchars($collegeInfo['college_name']); ?></strong>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Summary Section -->
            <?php if (!empty($data)): ?>
            <div class="summary-section">
                <div class="summary-title">Summary</div>
                <div class="summary-stats">
                    <?php
                    $totalSquads = count($data);
                    $totalActive = count(array_filter($data, function($row) { return $row['status'] === 'Active'; }));
                    $totalInactive = count(array_filter($data, function($row) { return $row['status'] === 'Inactive'; }));
                    $totalStaff = count(array_unique(array_column($data, 'staff_id')));
                    $totalDates = count(array_unique(array_column($data, 'exam_date')));
                    ?>
                    <div class="stat-item">
                        <div class="stat-number"><?php echo $totalSquads; ?></div>
                        <div class="stat-label">Total Squad Assignments</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number"><?php echo $totalStaff; ?></div>
                        <div class="stat-label">Staff Members</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number"><?php echo $totalDates; ?></div>
                        <div class="stat-label">Exam Dates</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number"><?php echo $totalActive; ?></div>
                        <div class="stat-label">Active</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number"><?php echo $totalInactive; ?></div>
                        <div class="stat-label">Inactive</div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Squad Table -->
            <table class="squad-table">
                <thead>
                    <tr>
                        <th class="date-session-header">Date & Session</th>
                        <th class="squad-name-header">Squad Name</th>
                        <th class="staff-header">Staff Name</th>
                        <th class="staff-header">Staff Code</th>
                        <th class="status-header">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($data)): ?>
                        <?php foreach ($data as $row): ?>
                        <tr>
                            <td>
                                <?php echo date('d-m-Y', strtotime($row['exam_date'])); ?><br>
                                <span class="session-badge session-<?php echo strtolower($row['session']); ?>">
                                    <?php echo $row['session']; ?>
                                </span>
                            </td>
                            <td><?php echo htmlspecialchars($row['squad_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['staff_code']); ?></td>
                            <td>
                                <span class="status-badge status-<?php echo strtolower($row['status']); ?>">
                                    <?php echo htmlspecialchars($row['status']); ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="5" style="text-align: center; padding: 20px; color: #666;">No squad assignments found for the selected criteria</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>

            <!-- Footer -->
            <div class="footer">
                <div class="footer-left">
                    <div>Date: _______________</div>
                    <div>Station: <?php echo $collegeInfo ? htmlspecialchars($collegeInfo['location']) : 'Nagapattinam'; ?></div>
                </div>
                <div class="footer-right">
                    <div>Signature of Chief Superintendent</div>
                    <div class="signature-line"></div>
                    <div style="margin-top: 5px;">with college seal</div>
                </div>
            </div>
        </div>

        <script>
            // Auto-print when page loads
            window.onload = function() {
                // Small delay to ensure page is fully loaded
                setTimeout(function() {
                    window.print();
                }, 500);
            };
            
            // Also handle print on key press (Ctrl+P)
            document.addEventListener('keydown', function(e) {
                if (e.ctrlKey && e.key === 'p') {
                    e.preventDefault();
                    window.print();
                }
            });
        </script>
    </body>
    </html>
    <?php

} catch (Exception $e) {
    echo "<h1>Error</h1>";
    echo "<p>An error occurred: " . htmlspecialchars($e->getMessage()) . "</p>";
    echo "<p><strong>Debug Info:</strong></p>";
    echo "<ul>";
    echo "<li>Exam Date: " . htmlspecialchars($_GET['exam_date'] ?? 'Not set') . "</li>";
    echo "<li>Session: " . htmlspecialchars($_GET['session'] ?? 'Not set') . "</li>";
    echo "<li>Staff ID: " . htmlspecialchars($_GET['staff_id'] ?? 'Not set') . "</li>";
    echo "<li>Status: " . htmlspecialchars($_GET['status'] ?? 'Not set') . "</li>";
    echo "</ul>";
    echo "<p><strong>Stack Trace:</strong></p>";
    echo "<pre>" . htmlspecialchars($e->getTraceAsString()) . "</pre>";
}
?>
