<?php
//filename: meeting_slip.php
include('session_validator.php');
include("includes/db.php");

// Fetch school details
$query = "SELECT * FROM schools LIMIT 1";
$result = $conn->query($query);

if ($result->num_rows > 0) {
    $schoolDetails = $result->fetch_assoc();
    $logoPath = $schoolDetails['logo'];
} else {
    $schoolDetails = [];
}

// Initialize variables
$className = '';
$sectionName = '';
$students = [];
$meetingTitle = 'Parent Meeting Attendance';

// Check if class_id and section_id are provided
if (isset($_GET['class_id']) && isset($_GET['section_id'])) {
    $classId = $_GET['class_id'];
    $sectionId = $_GET['section_id'];
    
    // Fetch class and section details
    $classQuery = "SELECT c.class_id, c.class, s.section_id, s.section_name 
                   FROM classes c
                   LEFT JOIN class_section cs ON c.class_id = cs.class_id
                   LEFT JOIN sections s ON cs.section_id = s.section_id
                   WHERE c.class_id = ? AND s.section_id = ?";
    $stmt = $conn->prepare($classQuery);
    $stmt->bind_param("ii", $classId, $sectionId);
    $stmt->execute();
    $classResult = $stmt->get_result();
    
    if ($classResult->num_rows > 0) {
        $classRow = $classResult->fetch_assoc();
        $className = $classRow['class'];
        $sectionName = $classRow['section_name'];
        $classNameFull = $className . " - " . $sectionName;
    }
    $stmt->close();
    
    // Fetch students for the selected class and section from student_class_section_data table
    // Get current academic year (you might need to adjust this based on your system)
    $currentAcademicYear = date('Y') . '-' . (date('Y') + 1);
    
    $studentsQuery = "SELECT s.student_id, s.regd_id, s.symbol_no, s.name, s.parent_name, s.parent_phone 
                      FROM students s
                      INNER JOIN student_class_section_data scsd ON s.student_id = scsd.student_id
                      WHERE scsd.class_id = ? 
                      AND scsd.section_id = ?
                      AND scsd.academic_year = ?
                      AND scsd.status = 'active'
                      ORDER BY s.name";
    
    $stmt = $conn->prepare($studentsQuery);
    $stmt->bind_param("iis", $classId, $sectionId, $currentAcademicYear);
    $stmt->execute();
    $studentsResult = $stmt->get_result();
    
    if ($studentsResult->num_rows > 0) {
        while ($studentRow = $studentsResult->fetch_assoc()) {
            $students[] = $studentRow;
        }
    } else {
        // If no students found with current academic year, try to get all students for that class/section
        $fallbackQuery = "SELECT s.student_id, s.regd_id, s.symbol_no, s.name, s.parent_name, s.parent_phone 
                         FROM students s
                         INNER JOIN student_class_section_data scsd ON s.student_id = scsd.student_id
                         WHERE scsd.class_id = ? 
                         AND scsd.section_id = ?
                         ORDER BY s.name";
        
        $stmt2 = $conn->prepare($fallbackQuery);
        $stmt2->bind_param("ii", $classId, $sectionId);
        $stmt2->execute();
        $fallbackResult = $stmt2->get_result();
        
        if ($fallbackResult->num_rows > 0) {
            while ($studentRow = $fallbackResult->fetch_assoc()) {
                $students[] = $studentRow;
            }
        }
        $stmt2->close();
    }
    $stmt->close();
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Parent Meeting Attendance Slip - <?php echo htmlspecialchars($classNameFull ?? 'Class'); ?></title>
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
    <link rel="stylesheet" href="css/prism/prism.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <style>
        /* Custom styles for meeting slip */
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f5f5f5;
        }
        
        .meeting-table {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .school-header {
            text-align: center;
            margin-bottom: 10px;
            border-bottom: 1px solid #007bff;
            padding-bottom: 10px;
        }
        
        .school-logo {
            max-height: 80px;
            margin-bottom: 5px;
        }
        
        .school-header h2 {
            font-size: 20px;
            margin: 5px 0;
        }
        
        .school-header p {
            margin: 2px 0;
            font-size: 12px;
        }
        
        .meeting-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 10px;
        }
        
        .meeting-table th {
            background-color: #007bff;
            color: white;
            padding: 6px 3px;
            text-align: center;
            border: 1px solid #dee2e6;
            font-size: 12px;
        }
        
        .meeting-table td {
            padding: 5px 3px;
            border: 1px solid #dee2e6;
            text-align: left;
            vertical-align: middle;
            font-size: 12px;
        }
        
        .meeting-table tr:nth-child(even) {
            background-color: #f8f9fa;
        }
        
        .signature-cell {
            height: 30px;
            border-bottom: 1px solid #dee2e6;
        }
        
        .print-button {
            margin-bottom: 15px;
        }
        
        .watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 60px;
            color: rgba(0,123,255,0.05);
            z-index: -1;
            pointer-events: none;
        }
        
        @media print {
            body {
                background-color: white;
                font-size: 10px;
                margin: 0;
                padding: 0;
            }
            
            .no-print {
                display: none !important;
            }
            
            .print-button {
                display: none !important;
            }
            
            .watermark {
                display: block;
                font-size: 40px;
            }
            
            .meeting-table {
                box-shadow: none;
                padding: 5px;
                margin: 0;
                border-radius: 0;
                page-break-inside: avoid;
            }
            
            .meeting-table {
                margin-bottom: 5px;
                page-break-inside: avoid;
            }
            
            .meeting-table th {
                padding: 3px 2px;
                font-size: 10px;
            }
            
            .meeting-table td {
                padding: 3px 2px;
                font-size: 10px;
            }
            
            .school-header {
                margin-bottom: 5px;
                padding-bottom: 5px;
            }
            
            .school-logo {
                max-height: 60px;
            }
            
            .school-header h2 {
                font-size: 16px;
                margin: 2px 0;
            }
            
            .school-header p {
                margin: 1px 0;
                font-size: 9px;
            }
            
            .signature-cell {
                height: 25px;
            }
            
            .footer-note {
                font-size: 8px;
                margin-top: 5px;
                padding-top: 5px;
            }
            
            @page {
                margin: 0.3cm;
                size: portrait;
            }
        }
        
        .footer-note {
            font-size: 10px;
            color: #666;
            text-align: center;
            margin-top: 5px;
            padding-top: 5px;
            border-top: 1px solid #dee2e6;
        }
        
        .warning-box {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 10px;
            margin-bottom: 15px;
            border-radius: 4px;
            font-size: 12px;
        }
        
        .class-section-title {
            font-size: 14px;
            font-weight: bold;
            color: #333;
            margin: 5px 0;
        }
    </style>
</head>
<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <!-- TOP NAVBAR -->
        <?php include('includes/topbar.php'); ?>

        <!-- SIDEBARS & MAIN CONTENT WRAPPER -->
        <div class="content-wrapper">
            <div class="content-container">
                <!-- LEFT SIDEBAR -->
                <?php include('includes/leftbar.php'); ?>

                <div class="main-page">
                    <div class="container-fluid">
                        <!-- PAGE TITLE -->
                        <div class="row page-title-div">
                            <div class="col-md-6">
                                <h2 class="title">Parent Meeting Attendance Slip</h2>
                            </div>
                        </div>

                        <!-- BREADCRUMBS -->
                        <div class="row breadcrumb-div">
                            <div class="col-md-6">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li><a href="select_class.php">Reports</a></li>
                                    <li class="active">Meeting Slip</li>
                                </ul>
                            </div>
                        </div>
                    </div>

                    <div class="container-fluid">
                        <div class="row">
                            <div class="col-md-12">
                                <div class="panel">
                                    <div class="panel-heading">
                                        <div class="panel-title">
                                            <h5>Parent Meeting Attendance Slip</h5>
                                        </div>
                                    </div>
                                    <div class="panel-body">
                                        <?php if (!isset($_GET['class_id']) || !isset($_GET['section_id'])): ?>
                                            <div class="alert alert-warning">
                                                <h4><i class="fa fa-exclamation-triangle"></i> Missing Parameters</h4>
                                                <p>Please select a class and section to generate the meeting slip.</p>
                                                <a href="select_class.php" class="btn btn-primary">
                                                    <i class="fa fa-arrow-left"></i> Go Back to Selection
                                                </a>
                                            </div>
                                        <?php elseif (empty($students)): ?>
                                            <div class="alert alert-warning">
                                                <h4><i class="fa fa-exclamation-triangle"></i> No Students Found</h4>
                                                <p>No active students found in <?php echo htmlspecialchars($classNameFull ?? 'selected class'); ?> for the current academic year.</p>
                                                <div class="warning-box">
                                                    <h6><i class="fa fa-info-circle"></i> Note:</h6>
                                                    <p>The system is now using the new student-class-section structure. Please ensure:</p>
                                                    <ol class="mb-0">
                                                        <li>Students are assigned to classes/sections in the <strong>student_class_section_data</strong> table</li>
                                                        <li>The academic year is correctly set</li>
                                                        <li>Student status is marked as 'active'</li>
                                                    </ol>
                                                </div>
                                                <a href="select_class.php" class="btn btn-primary">
                                                    <i class="fa fa-arrow-left"></i> Go Back to Selection
                                                </a>
                                            </div>
                                        <?php else: ?>
                                            <div class="no-print print-button">
                                                <button onclick="printMeetingSlip()" class="btn btn-success">
                                                    <i class="fa fa-print"></i> Print Meeting Slip
                                                </button>
                                                <a href="select_class.php" class="btn btn-primary">
                                                    <i class="fa fa-arrow-left"></i> Generate Another
                                                </a>
                                                <a href="dashboard.php" class="btn btn-default">
                                                    <i class="fa fa-home"></i> Dashboard
                                                </a>
                                            </div>
                                            
                                            <!-- Watermark for print -->
                                            <div class="watermark no-print">
                                                <?php echo htmlspecialchars($schoolDetails['school_name'] ?? 'SCHOOL'); ?>
                                            </div>
                                         
                                            <!-- Meeting Slip Container -->
                                            <div class="meeting-table">
                                                <table class="meeting-table">
                                                    <thead>
                                                        <tr>
                                                            <td class="logo-cell" colspan="2">
                                                                <?php if (!empty($logoPath)): ?>
                                                                    <img src="<?php echo htmlspecialchars($logoPath); ?>" 
                                                                         alt="School Logo" class="school-logo">
                                                                <?php endif; ?>
                                                            </td>
                                                            <td class="school-info-cell" colspan="4" style="text-align:center;">
                                                                <h2 style="margin:0; line-height:1.2;">
                                                                    <?php echo htmlspecialchars($schoolDetails['school_name'] ?? 'School Name'); ?>
                                                                </h2>
                                                                <h4 style="margin:2px 0; font-weight:normal; line-height:1.2;">
                                                                    <?php echo htmlspecialchars($schoolDetails['address'] ?? 'School Address'); ?>
                                                                </h4>
                                                                <div style="margin:0; font-size:14px; line-height:1.2;">
                                                                    <strong>Phone:</strong> <?php echo htmlspecialchars($schoolDetails['phone'] ?? 'N/A'); ?>
                                                                    &nbsp;|&nbsp;
                                                                    <strong>Email:</strong> <?php echo htmlspecialchars($schoolDetails['email'] ?? 'N/A'); ?>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <td style="color: none; text-align: center; font-size: 14px; font-weight: bold;" colspan="6">
                                                                दोस्रो आन्तरिक परीक्षा अभिभावक उपस्थिति
                                                                <?php if (!empty($className) && !empty($sectionName)): ?>
                                                                    <span style="font-weight: normal;">(<?php echo htmlspecialchars($className); ?> - <?php echo htmlspecialchars($sectionName); ?>)</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                        <tr>
                                                            <th style="width: 8%;">S.N.</th>
                                                            <th style="width: 10%;">Student ID</th>
                                                            <th style="width: 20%;">Student Name</th>
                                                            <th style="width: 20%;">Parent/Guardian Name</th>
                                                            <th style="width: 20%;">Contact Number</th>
                                                            <th style="width: 15%;">Signature</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($students as $index => $student): ?>
                                                        <tr>
                                                            <td style="text-align: center;"><?php echo $index + 1; ?></td>
                                                            <td style="text-align: center;">
                                                                <?php echo htmlspecialchars($student['regd_id'] ?? 'N/A'); ?>
                                                            </td>
                                                            <td><?php echo htmlspecialchars($student['name'] ?? 'N/A'); ?></td>
                                                            <td></td>
                                                            <td></td>
                                                            <td class="signature-cell"></td>
                                                        </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                                
                                                <!-- Footer Notes -->
                                                <div class="footer-note">
                                                    <p>
                                                        <strong>Class Teacher:</strong> _________________________ &nbsp;&nbsp;&nbsp;
                                                        <strong>Head Teacher:</strong> _________________________
                                                    </p>
                                                </div>
                                                
                                                <!-- Print Statistics -->
                                                <div class="text-center text-muted small mt-2">
                                                    <p>Generated on: <?php echo date('F j, Y, g:i a'); ?> | 
                                                       Total Students: <?php echo count($students); ?></p>
                                                </div>
                                            </div>
                                            
                                            <div class="no-print print-button mt-3">
                                                <button onclick="printMeetingSlip()" class="btn btn-success">
                                                    <i class="fa fa-print"></i> Print Meeting Slip
                                                </button>
                                                <button onclick="downloadAsPDF()" class="btn btn-danger">
                                                    <i class="fa fa-file-pdf-o"></i> Download as PDF
                                                </button>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- JavaScript includes -->
        <script src="js/jquery/jquery-2.2.4.min.js"></script>
        <script src="js/bootstrap/bootstrap.min.js"></script>
        <script src="js/pace/pace.min.js"></script>
        <script src="js/lobipanel/lobipanel.min.js"></script>
        <script src="js/iscroll/iscroll.js"></script>
        <script src="js/prism/prism.js"></script>
        <script src="js/select2/select2.min.js"></script>
        <script src="js/main.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
        
        <script>
        function printMeetingSlip() {
            // Store original body content
            var originalContent = document.body.innerHTML;
            
            // Get only the meeting slip content
            var meetingSlipContent = document.querySelector('.meeting-table').outerHTML;
            
            // Create a new window for printing
            var printWindow = window.open('', '_blank');
            
            // Write the print document
            printWindow.document.write(`
                <!DOCTYPE html>
                <html>
                <head>
                    <title>Parent Meeting Attendance Slip - <?php echo htmlspecialchars($classNameFull); ?></title>
                    <style>
                        @page {
                            margin: 0.5cm;
                            size: portrait;
                        }
                        body {
                            font-family: 'Arial', sans-serif;
                            font-size: 14px;
                            line-height: 1.2;
                            margin: 0;
                            padding: 0;
                        }
                        .meeting-table {
                            padding: 3px;
                            margin: 0;
                            page-break-inside: avoid;
                        }
                        .school-logo {
                            max-height: 60px;
                            margin-bottom: 2px;
                        }
                        .meeting-table {
                            width: 100%;
                            border-collapse: collapse;
                            margin-bottom: 3px;
                            font-size: 9px;
                            page-break-inside: avoid;
                        }
                        .meeting-table th {
                            background-color: #333;
                            color: white;
                            padding: 2px 1px;
                            text-align: center;
                            border: 1px solid #000;
                            font-size: 9px;
                        }
                        .meeting-table td {
                            padding: 6px 1px;
                            border: 1px solid #000;
                            text-align: left;
                            font-size: 12px;
                        }
                        .meeting-table tr:nth-child(even) {
                            background-color: #f0f0f0;
                        }
                        .signature-cell {
                            height: 20px;
                            border-bottom: 1px solid #000;
                        }
                        .footer-note {
                            font-size: 7px;
                            color: #666;
                            text-align: center;
                            margin-top: 3px;
                            padding-top: 3px;
                            border-top: 1px solid #000;
                        }
                        .watermark {
                            position: fixed;
                            top: 50%;
                            left: 50%;
                            transform: translate(-50%, -50%) rotate(-45deg);
                            font-size: 30px;
                            color: rgba(0,0,0,0.05);
                            z-index: -1;
                            pointer-events: none;
                        }
                    </style>
                </head>
                <body>
                    <div class="watermark"><?php echo htmlspecialchars($schoolDetails['school_name'] ?? 'SCHOOL'); ?></div>
                    <div class="meeting-table">
                        ${meetingSlipContent}
                    </div>
                </body>
                </html>
            `);
            
            printWindow.document.close();
            
            // Wait a bit for the content to load, then print
            setTimeout(function() {
                printWindow.print();
                printWindow.close();
            }, 250);
        }
        
        function downloadAsPDF() {
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF('p', 'mm', 'a4');
            
            // Get the meeting slip container
            const element = document.querySelector('.meeting-table');
            
            // Set PDF options for better quality
            const pdfOptions = {
                scale: 2, // Increase scale for better quality
                useCORS: true, // Allow cross-origin images
                logging: false
            };
            
            html2canvas(element, pdfOptions).then(canvas => {
                const imgData = canvas.toDataURL('image/png');
                const imgWidth = 190; // A4 width in mm minus margins
                const pageHeight = 280; // A4 height in mm
                const imgHeight = canvas.height * imgWidth / canvas.width;
                
                // Check if content fits on one page
                if (imgHeight > pageHeight) {
                    // Split content if it's too long
                    const pages = Math.ceil(imgHeight / pageHeight);
                    let position = 0;
                    
                    for(let i = 0; i < pages; i++) {
                        if (i > 0) {
                            doc.addPage();
                            position = -pageHeight * i;
                        }
                        
                        doc.addImage(imgData, 'PNG', 10, position + 10, imgWidth, imgHeight);
                    }
                } else {
                    // Single page
                    doc.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);
                }
                
                // Save the PDF
                doc.save('Meeting_Slip_<?php echo preg_replace("/[^a-zA-Z0-9]/", "_", $classNameFull); ?>_<?php echo date('Y_m_d'); ?>.pdf');
            });
        }
        </script>
    </body>
</html>