<?php
session_start();
require_once 'config/database.php';
require_once 'includes/site_settings.php';

// Get site settings
$settings = get_all_settings($pdo);
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$site_address = $settings['site_address'] ?? 'ঠিকানা: গ্রাম/থানা, জেলা, বাংলাদেশ';
$logo_image = $settings['logo_image'] ?? null;
$logo_size = isset($settings['logo_size']) ? intval($settings['logo_size']) : 100;

// Check if application number or student ID is provided
$application = null;
$application_no = isset($_GET['application_no']) ? trim($_GET['application_no']) : '';
$student_id = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0;

// Initialize subjects array
$subjects = [];

if (!empty($application_no)) {
    try {
        $stmt = $pdo->prepare("SELECT aa.*, c.name as class_name, c.section as class_section FROM admission_applications aa LEFT JOIN classes c ON aa.applying_for_class_id = c.id WHERE aa.application_no = ?");
        $stmt->execute([$application_no]);
        $application = $stmt->fetch();
    } catch (Exception $e) {
        $error_message = 'আবেদন তথ্য আনতে সমস্যা হয়েছে।';
    }
} elseif ($student_id > 0) {
    // If student ID is provided, get student data to pre-fill the form
    try {
        $stmt = $pdo->prepare("SELECT s.*, c.name as class_name, c.section as class_section FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
        $stmt->execute([$student_id]);
        $student = $stmt->fetch();
        
        if ($student) {
            // Create a mock application object from student data
            $application = [
                'application_no' => 'STU-' . $student['id'],
                'first_name' => $student['first_name'],
                'last_name' => $student['last_name'],
                'father_name' => $student['father_name'],
                'mother_name' => $student['mother_name'],
                'date_of_birth' => $student['date_of_birth'],
                'gender' => $student['gender'],
                'religion' => $student['religion'], // Fixed: Include religion from student data
                'blood_group' => $student['blood_group'],
                'phone' => $student['phone'],
                'father_phone' => $student['guardian_phone'],
                'email' => $student['email'],
                'present_address' => $student['address'],
                'permanent_address' => $student['address'],
                'class_name' => $student['class_name'],
                'section' => $student['class_section'] ?? '', // Fixed: Use the correct column name
                'applying_for_session' => $student['session'],
                'applying_for_group' => $student['group_name'],
                'previous_class' => $student['previous_class'] ?? '',
                'previous_school' => $student['previous_school'] ?? '',
                'photo_path' => $student['photo'],
                'status' => $student['status'],
                'created_at' => $student['created_at'],
                'approved_at' => '',
                'reviewed_by_name' => '',
                'admin_remarks' => 'প্রিন্ট ফরম - ছাত্র/ছাত্রী থেকে তথ্য নেওয়া'
            ];
            
            // Get student's subjects
            $stmt = $pdo->prepare("
                SELECT s.name, s.code
                FROM subjects s
                JOIN student_subjects ss ON s.id = ss.subject_id
                WHERE ss.student_id = ?
                ORDER BY s.name
            ");
            $stmt->execute([$student_id]);
            $subjects = $stmt->fetchAll();
        }
    } catch (Exception $e) {
        $error_message = 'ছাত্র/ছাত্রী তথ্য আনতে সমস্যা হয়েছে।';
    }
}

// If no application or student found, redirect to admission application page
if (!$application) {
    header('Location: admission_application.php');
    exit();
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        <?php if ($student_id > 0): ?>
            ছাত্র/ছাত্রী তথ্য ফরম - <?php echo htmlspecialchars($site_name); ?>
        <?php else: ?>
            ভর্তি আবেদন ফরম - <?php echo htmlspecialchars($site_name); ?>
        <?php endif; ?>
    </title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { 
            font-family: 'Hind Siliguri', sans-serif;
            background: #ffffff;
            font-size: 14px;
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            body {
                background: white;
                font-size: 12px;
            }
            .student-photo {
                /* Ensure photo is visible in print */
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
            .print-section {
                page-break-inside: avoid;
            }
            .form-control-plaintext {
                border-bottom: 1px solid #000 !important;
                min-height: 24px;
            }
        }
        
        .form-header {
            background: #f8f9fa;
            border-bottom: 2px solid #006747;
            padding: 1rem 0;
            margin-bottom: 1.5rem;
        }
        
        .form-card {
            background: white;
            border: 1px solid #e0e0e0;
            margin-bottom: 1rem;
        }
        
        .section-title {
            color: #006747;
            border-bottom: 2px solid #006747;
            padding-bottom: 8px;
            margin-bottom: 15px;
            font-weight: 700;
            font-size: 1.2rem;
        }
        
        .info-row {
            margin-bottom: 8px;
        }
        
        .info-label {
            font-weight: 600;
            color: #006747;
            display: inline-block;
            width: 160px;
            vertical-align: top;
        }
        
        .form-control-plaintext {
            display: inline-block;
            width: calc(100% - 170px);
            border-bottom: 1px dashed #ccc;
            min-height: 24px;
            padding: 2px 0;
        }
        
        .signature-section {
            margin-top: 3rem;
            border-top: 1px solid #000;
            padding-top: 10px;
            text-align: right;
        }
        
        .student-photo {
            max-width: 120px;
            max-height: 150px;
            border: 1px solid #006747;
            border-radius: 3px;
        }
        
        .form-table {
            width: 100%;
            border-collapse: collapse;
            margin: 1rem 0;
        }
        
        .form-table td, .form-table th {
            border: 1px solid #000;
            padding: 8px;
            text-align: left;
        }
        
        .form-table th {
            background-color: #f0f0f0;
            font-weight: bold;
        }
        
        .text-center {
            text-align: center;
        }
        
        .text-right {
            text-align: right;
        }
        
        .fw-bold {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="form-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-2 text-center">
                    <?php if ($logo_image): ?>
                        <img src="<?php echo htmlspecialchars($logo_image); ?>" alt="Logo" class="img-fluid" style="max-height: <?php echo $logo_size; ?>px;">
                    <?php else: ?>
                        <div class="bg-light border rounded-circle d-flex align-items-center justify-content-center" style="width: <?php echo $logo_size; ?>px; height: <?php echo $logo_size; ?>px; margin: 0 auto;">
                            <i class="fas fa-school fa-2x text-success"></i>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="col-md-10 text-center">
                    <h2><?php echo htmlspecialchars($site_name); ?></h2>
                    <h3>
                        <?php if ($student_id > 0): ?>
                            ছাত্র/ছাত্রী তথ্য ফরম
                        <?php else: ?>
                            ভর্তি আবেদন ফরম
                        <?php endif; ?>
                    </h3>
                    <p>আবেদন নং: <?php echo htmlspecialchars($application['application_no']); ?></p>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="form-card">
            <div class="card-body p-4">
                <div class="no-print text-end mb-3">
                    <button class="btn btn-success" onclick="window.print()">
                        <i class="fas fa-print"></i> প্রিন্ট করুন
                    </button>
                    <?php if ($student_id > 0): ?>
                        <a href="teachers/my_students.php" class="btn btn-primary">
                            <i class="fas fa-arrow-left"></i> ছাত্র-ছাত্রী তালিকায় ফিরুন
                        </a>
                    <?php else: ?>
                        <a href="admission_receipt.php?application_no=<?php echo urlencode($application['application_no']); ?>" class="btn btn-primary">
                            <i class="fas fa-arrow-left"></i> রশিদ দেখুন
                        </a>
                    <?php endif; ?>
                </div>
                
                <!-- Personal Information Section -->
                <div class="print-section">
                    <h4 class="section-title"><i class="fas fa-user"></i> ব্যক্তিগত তথ্য</h4>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="info-row">
                                        <span class="info-label">নাম (প্রথম):</span>
                                        <span class="form-control-plaintext"><?php echo htmlspecialchars($application['first_name']); ?></span>
                                    </div>
                                    
                                    <div class="info-row">
                                        <span class="info-label">পিতার নাম:</span>
                                        <span class="form-control-plaintext"><?php echo htmlspecialchars($application['father_name']); ?></span>
                                    </div>
                                    
                                    <div class="info-row">
                                        <span class="info-label">জন্ম তারিখ:</span>
                                        <span class="form-control-plaintext"><?php echo date('d/m/Y', strtotime($application['date_of_birth'])); ?></span>
                                    </div>
                                    
                                    <div class="info-row">
                                        <span class="info-label">ধর্ম:</span>
                                        <span class="form-control-plaintext">
                                            <?php 
                                                switch($application['religion']) {
                                                    case 'islam': echo 'ইসলাম'; break;
                                                    case 'hinduism': echo 'হিন্দু'; break;
                                                    case 'buddhism': echo 'বৌদ্ধ'; break;
                                                    case 'christianity': echo 'খ্রিস্টান'; break;
                                                    case 'other': echo 'অন্যান্য'; break;
                                                    default: echo '';
                                                }
                                            ?>
                                        </span>
                                    </div>
                                    
                                    <div class="info-row">
                                        <span class="info-label">রক্তের গ্রুপ:</span>
                                        <span class="form-control-plaintext"><?php echo htmlspecialchars($application['blood_group'] ?? ''); ?></span>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="info-row">
                                        <span class="info-label">নাম (শেষ):</span>
                                        <span class="form-control-plaintext"><?php echo htmlspecialchars($application['last_name']); ?></span>
                                    </div>
                                    
                                    <div class="info-row">
                                        <span class="info-label">মাতার নাম:</span>
                                        <span class="form-control-plaintext"><?php echo htmlspecialchars($application['mother_name']); ?></span>
                                    </div>
                                    
                                    <div class="info-row">
                                        <span class="info-label">লিঙ্গ:</span>
                                        <span class="form-control-plaintext">
                                            <?php 
                                                echo ($application['gender'] == 'male') ? 'পুরুষ' : 
                                                    (($application['gender'] == 'female') ? 'মহিলা' : 'অন্যান্য'); 
                                            ?>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4 text-center">
                            <?php if (!empty($application['photo_path']) && file_exists($application['photo_path'])): ?>
                                <img src="<?php echo htmlspecialchars($application['photo_path']); ?>" alt="Student Photo" class="student-photo">
                            <?php else: ?>
                                <div class="student-photo d-flex align-items-center justify-content-center bg-light">
                                    <i class="fas fa-user fa-3x text-muted"></i>
                                </div>
                            <?php endif; ?>
                            <p class="mt-2"><small>ছাত্র/ছাত্রীর ছবি</small></p>
                        </div>
                    </div>
                </div>
                
                <!-- Contact Information Section -->
                <div class="print-section mt-4">
                    <h4 class="section-title"><i class="fas fa-phone"></i> যোগাযোগের তথ্য</h4>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <table class="form-table">
                                <tr>
                                    <td><strong>ছাত্র/ছাত্রীর ফোন:</strong> <?php echo htmlspecialchars($application['phone']); ?></td>
                                    <td><strong>পিতা/অভিভাবকের ফোন:</strong> <?php echo htmlspecialchars($application['father_phone'] ?? ''); ?></td>
                                    <td><strong>ইমেইল:</strong> <?php echo htmlspecialchars($application['email'] ?? ''); ?></td>
                                    <td><strong>ঠিকানা:</strong> <?php echo htmlspecialchars($application['present_address'] ?? ''); ?></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Academic Information Section -->
                <div class="print-section mt-4">
                    <h4 class="section-title"><i class="fas fa-graduation-cap"></i> শিক্ষাগত তথ্য</h4>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <table class="form-table">
                                <tr>
                                    <td><strong>আবেদন করা ক্লাস:</strong> <?php echo htmlspecialchars($application['class_name'] . ($application['section'] ? ' - ' . $application['section'] : '')); ?></td>
                                    <td><strong>সেশন:</strong> <?php echo htmlspecialchars($application['applying_for_session'] ?? ''); ?></td>
                                    <td><strong>গ্রুপ:</strong> <?php echo htmlspecialchars($application['applying_for_group'] ?? ''); ?></td>
                                    <td><strong>বিষয়সমূহ:</strong> 
                                        <?php 
                                        if (!empty($subjects)) {
                                            $subject_list = [];
                                            foreach ($subjects as $subject) {
                                                $subject_list[] = htmlspecialchars($subject['name'] . ' (' . $subject['code'] . ')');
                                            }
                                            echo implode(', ', $subject_list);
                                        } else {
                                            echo ($student_id > 0) ? 'কোন বিষয় নির্বাচন করা হয়নি' : '';
                                        }
                                        ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td><strong>পূর্ববর্তী ক্লাস:</strong> <?php echo htmlspecialchars($application['previous_class'] ?? ''); ?></td>
                                    <td><strong>পূর্ববর্তী স্কুল:</strong> <?php echo htmlspecialchars($application['previous_school'] ?? ''); ?></td>
                                    <td colspan="2"></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Declaration Section -->
                <div class="print-section mt-4">
                    <h4 class="section-title"><i class="fas fa-file-signature"></i> ঘোষণা ও স্বাক্ষর</h4>
                    
                    <div class="row">
                        <div class="col-md-12">
                            <p>আমি নিশ্চয়তার সাথে ঘোষণা করছি যে, উপরে উল্লিখিত সকল তথ্য সত্য ও সঠিক। ভুয়া তথ্য প্রদানের ফলে আমি যে কোন শাস্তি গ্রহণ করতে রাজি আছি।</p>
                            
                            <div class="row mt-5">
                                <div class="col-md-4 text-center">
                                    <div class="signature-section">
                                        <p>আবেদনকারীর স্বাক্ষর</p>
                                    </div>
                                </div>
                                <div class="col-md-4 text-center">
                                    <div class="signature-section">
                                        <p>পিতা/অভিভাবকের স্বাক্ষর</p>
                                    </div>
                                </div>
                                <div class="col-md-4 text-center">
                                    <div class="signature-section">
                                        <p>কর্তৃপক্ষের স্বাক্ষর</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Office Use Section -->
                <div class="print-section mt-4">
                    <h4 class="section-title"><i class="fas fa-building"></i> কার্যালয়ের ব্যবহারের জন্য</h4>
                    
                    <table class="form-table">
                        <tr>
                            <th>বিবরণ</th>
                            <th>তথ্য</th>
                        </tr>
                        <tr>
                            <td>আবেদনের/তৈরির তারিখ</td>
                            <td><?php echo date('d/m/Y H:i', strtotime($application['created_at'])); ?></td>
                        </tr>
                        <?php if ($student_id == 0): ?>
                        <tr>
                            <td>অবস্থা</td>
                            <td>
                                <?php 
                                    if ($application['status'] == 'pending') echo 'মুলতুবি';
                                    elseif ($application['status'] == 'approved') echo 'অনুমোদিত';
                                    elseif ($application['status'] == 'rejected') echo 'প্রত্যাখ্যাত';
                                    else echo 'বাতিল';
                                ?>
                            </td>
                        </tr>
                        <tr>
                            <td>পর্যালোচনাকারী</td>
                            <td><?php echo htmlspecialchars($application['reviewed_by_name'] ?? ''); ?></td>
                        </tr>
                        <tr>
                            <td>পর্যালোচনার তারিখ</td>
                            <td><?php echo $application['approved_at'] ? date('d/m/Y H:i', strtotime($application['approved_at'])) : ''; ?></td>
                        </tr>
                        <tr>
                            <td>প্রশাসনের মন্তব্য</td>
                            <td><?php echo htmlspecialchars($application['admin_remarks'] ?? ''); ?></td>
                        </tr>
                        <?php else: ?>
                        <tr>
                            <td>অবস্থা</td>
                            <td>
                                <?php 
                                    if ($application['status'] == 'active') echo 'সক্রিয়';
                                    elseif ($application['status'] == 'inactive') echo 'নিষ্ক্রিয়';
                                    elseif ($application['status'] == 'graduated') echo 'স্নাতক';
                                    else echo 'স্থানান্তরিত';
                                ?>
                            </td>
                        </tr>
                        <tr>
                            <td>মন্তব্য</td>
                            <td><?php echo htmlspecialchars($application['admin_remarks'] ?? ''); ?></td>
                        </tr>
                        <?php endif; ?>
                    </table>
                </div>
                
                <div class="no-print text-center mt-4">
                    <button class="btn btn-success" onclick="window.print()">
                        <i class="fas fa-print"></i> প্রিন্ট করুন
                    </button>
                    <?php if ($student_id > 0): ?>
                        <a href="teachers/my_students.php" class="btn btn-primary">
                            <i class="fas fa-arrow-left"></i> ছাত্র-ছাত্রী তালিকায় ফিরুন
                        </a>
                    <?php else: ?>
                        <a href="admission_receipt.php?application_no=<?php echo urlencode($application['application_no']); ?>" class="btn btn-primary">
                            <i class="fas fa-arrow-left"></i> রশিদ দেখুন
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Auto print when page loads
        window.addEventListener('DOMContentLoaded', function() {
            // Uncomment the line below if you want auto-print on page load
            // window.print();
        });
    </script>
</body>
</html>