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

// Get site settings
$settings = get_all_settings($pdo);

// Primary source: site_settings table (from /admin/site_settings.php)
$site_name = $settings['site_name'] ?? 'বিদ্যা নিকেতন';
$site_address = $settings['site_address'] ?? '';
$logo_image = $settings['logo_image'] ?? $settings['header_image'] ?? $settings['school_logo'] ?? null;

// Debug: Check what's in the settings array
echo "<!-- Debug: Settings array keys: " . implode(',', array_keys($settings)) . " -->";

// Secondary source: settings table (from /admin/settings.php) - only if not found in site_settings
if (empty($site_name) || $site_name === 'বিদ্যা নিকেতন') {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'school_name' OR setting_key = 'system_name' OR setting_key = 'site_name' LIMIT 1");
    $stmt->execute();
    $result = $stmt->fetch();
    if ($result) {
        $site_name = $result['setting_value'];
    }
}

if (empty($site_address)) {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'school_address' OR setting_key = 'address' LIMIT 1");
    $stmt->execute();
    $result = $stmt->fetch();
    if ($result) {
        $site_address = $result['setting_value'];
    }
}

if (empty($logo_image)) {
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'school_logo' OR setting_key = 'logo_image' LIMIT 1");
    $stmt->execute();
    $result = $stmt->fetch();
    if ($result) {
        $logo_image = $result['setting_value'];
    }
}

// Final debug: Output the values (remove HTML comments to see in source)
echo "<!-- Debug: site_name='{$site_name}', site_address='{$site_address}', logo_image='{$logo_image}' -->";

// Check if application number is provided
$application = null;
$application_no = isset($_GET['application_no']) ? trim($_GET['application_no']) : '';

if (!empty($application_no)) {
    try {
        $stmt = $pdo->prepare("SELECT aa.*, c.name as class_name, c.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();
        
        // If application is found, fetch outstanding fees for the student
        if ($application) {
            $outstanding_fees = [];
            
            // First, try to find if this application has been converted to a student record
            $stmt = $pdo->prepare("SELECT id FROM students WHERE phone = ? AND first_name = ? AND last_name = ? LIMIT 1");
            $stmt->execute([$application['phone'], $application['first_name'], $application['last_name']]);
            $student = $stmt->fetch();
            
            if ($student) {
                $student_id = $student['id'];
                
                // Fetch outstanding fees for this student
                $stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id = ? AND (status = 'pending' OR status = 'partial') ORDER BY due_date ASC");
                $stmt->execute([$student_id]);
                $outstanding_fees = $stmt->fetchAll();
            } else {
                // If student not found in students table, try to match by application number or other identifiers
                // For admission applications, fees might be associated directly with the application
                // or we can try to match based on the application number if it's stored in fees table
                // This is a fallback for when the student is not yet converted to a full student record
                
                // For now, we'll check if there are any fees associated with this phone number
                // by checking the students table for records with this phone
                $stmt = $pdo->prepare("SELECT id FROM students WHERE phone = ? LIMIT 1");
                $stmt->execute([$application['phone']]);
                $possible_students = $stmt->fetchAll();
                
                foreach ($possible_students as $possible_student) {
                    $stmt = $pdo->prepare("SELECT * FROM fees WHERE student_id = ? AND (status = 'pending' OR status = 'partial') ORDER BY due_date ASC");
                    $stmt->execute([$possible_student['id']]);
                    $fees = $stmt->fetchAll();
                    
                    if (!empty($fees)) {
                        $outstanding_fees = $fees;
                        break;
                    }
                }
            }
        }
    } catch (Exception $e) {
        $error_message = 'আবেদন তথ্য আনতে সমস্যা হয়েছে।';
    }
}

// If no application found, show error message
if (!$application) {
    ?>
    <!DOCTYPE html>
    <html lang="bn">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title> আবেদন তথ্য পাওয়া যায়নি - <?php echo htmlspecialchars($site_name); ?></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: #f5f7fa; 
            }
        </style>
    </head>
    <body>
        <div class="container mt-5">
            <div class="alert alert-danger text-center">
                <h4><i class="fas fa-exclamation-triangle"></i> তথ্য পাওয়া যায়নি</h4>
                <p>আবেদন নম্বর: <strong><?php echo htmlspecialchars($application_no); ?></strong></p>
                <p>দুঃখিত, আপনার নির্দিষ্ট করা আবেদন নম্বরের কোনো তথ্য পাওয়া যায়নি।</p>
                <a href="admission_application.php" class="btn btn-primary mt-2"><i class="fas fa-arrow-left"></i> নতুন আবেদন</a>
            </div>
        </div>
    </body>
    </html>
    <?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 echo htmlspecialchars($site_name); ?></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: #f5f7fa; 
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            body {
                background: white;
            }
            .student-photo {
                /* Ensure photo is visible in print */
                -webkit-print-color-adjust: exact;
                color-adjust: exact;
            }
        }
        
        .receipt-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: #fff;
            padding: 1.5rem 0;
            margin-bottom: 2rem;
            border-bottom: 3px solid #F42A41;
        }
        
        .receipt-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,103,71,0.15);
            border: 1px solid #e0e0e0;
            margin-bottom: 2rem;
        }
        
        .section-title {
            color: #006747;
            border-bottom: 2px solid #F42A41;
            padding-bottom: 10px;
            margin-bottom: 20px;
            font-weight: 700;
        }
        
        .info-row {
            margin-bottom: 10px;
        }
        
        .info-label {
            font-weight: 600;
            color: #006747;
            display: inline-block;
            width: 180px;
        }
        
        .status-badge {
            font-size: 1rem;
            padding: 0.5em 1em;
        }
        
        .student-photo {
            max-width: 150px;
            max-height: 200px;
            border: 2px solid #006747;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <!-- Top Institution Info -->
    <div class="container mt-3">
        <div class="position-relative">
            <?php if ($logo_image): ?>
                <div class="position-absolute start-0 top-0">
                    <img src="<?php echo htmlspecialchars($logo_image); ?>" alt="Institution Logo" style="max-height: 80px; max-width: 80px;">
                </div>
            <?php endif; ?>
            <div class="text-center">
                <h2 class="mb-1" style="color: #006747; font-weight: bold; margin-left: 90px;"><?php echo htmlspecialchars($site_name); ?></h2>
                <p class="mb-1" style="color: #006747; font-size: 1.1rem; margin-left: 90px;"><?php echo htmlspecialchars($site_address); ?></p>
            </div>
        </div>
    </div>
    
    <!-- Header -->
    <div class="receipt-header">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <!-- Institution Logo on the left -->
                    <?php if ($logo_image): ?>
                        <div class="text-start mb-2">
                            <img src="<?php echo htmlspecialchars($logo_image); ?>" alt="Institution Logo" style="max-height: 80px; max-width: 100px;">
                        </div>
                    <?php endif; ?>                    
                    <h1><i class="fas fa-receipt"></i> অনলাইন ভর্তি আবেদন ফরম</h1>
                </div>
                
                <div class="col-md-6 text-md-end">
                    <!-- Student Photo on the right -->
                    <?php if (!empty($application['photo_path'])): ?>
                        <div class="text-end mb-2">
                            <img src="<?php echo (!preg_match('/^https?:\/\//', $application['photo_path'])) ? '.' . htmlspecialchars($application['photo_path']) : htmlspecialchars($application['photo_path']); ?>" alt="Student Photo" style="max-height: 80px; max-width: 60px; border: 2px solid #fff; border-radius: 5px; object-fit: cover;">
                        </div>
                    <?php else: ?>
                        <div class="text-end mb-2">
                            <i class="fas fa-user-circle" style="font-size: 80px; color: #ccc; border: 2px solid #fff; border-radius: 5px;"></i>
                        </div>
                    <?php endif; ?>                    
                    <div class="no-print">
                        <button class="btn btn-light" onclick="window.print()">
                            <i class="fas fa-print"></i> প্রিন্ট করুন
                        </button>
                        <a href="admission_application.php" class="btn btn-light">
                            <i class="fas fa-arrow-left"></i> নতুন আবেদন
                        </a>
                        <a href="index.php" class="btn btn-light">
                            <i class="fas fa-home"></i> হোম পেজ
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="receipt-card">
            <div class="card-body p-4">
                <div class="text-center mb-4">
                    <h3> অনলাইন ভর্তি আবেদন ফরম</h3>
                    <div class="row justify-content-center">
                        <div class="col-auto">
                            <p class="d-inline-block me-4">আবেদন নং: <strong><?php echo htmlspecialchars($application['application_no']); ?></strong></p>
                        </div>
                        <div class="col-auto">
                            <p class="d-inline-block">আবেদনের তারিখ: <?php echo date('d/m/Y H:i', strtotime($application['created_at'])); ?></p>
                        </div>
                    </div>
                    
                    <?php if ($application['status'] == 'pending'): ?>
                        <span class="badge bg-warning status-badge">মুলতুবি</span>
                    <?php elseif ($application['status'] == 'approved'): ?>
                        <span class="badge bg-success status-badge">অনুমোদিত</span>
                    <?php elseif ($application['status'] == 'rejected'): ?>
                        <span class="badge bg-danger status-badge">প্রত্যাখ্যাত</span>
                    <?php else: ?>
                        <span class="badge bg-secondary status-badge">বাতিল</span>
                    <?php endif; ?>
                </div>
                
                <!-- Outstanding fees information for bank payment (moved to top) -->
                <?php if (!empty($outstanding_fees) && is_array($outstanding_fees)): ?>
                <?php 
                    // Calculate total outstanding amount
                    $total_due = 0;
                    foreach ($outstanding_fees as $fee) {
                        $due_amount = $fee['amount'] - $fee['paid_amount'];
                        $total_due += $due_amount;
                    }
                ?>
                <div class="card mb-4">
                    <div class="card-header bg-success text-white">
                        <h4 class="mb-0"><i class="fas fa-money-bill-wave"></i> বকেয়া ফি তথ্য - ব্যাংকে জমা দেয়ার জন্য</h4>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-danger text-center">
                            <h4 class="mb-2">মোট বকেয়া: <strong><?php echo number_format($total_due, 2); ?> টাকা</strong></h4>
                            <p class="mb-0">আপনার জমা দেওয়া ফি টাকা: <strong><?php echo number_format(array_sum(array_column($outstanding_fees, 'paid_amount')), 2); ?> টাকা</strong></p>
                        </div>
                        
                        <div class="alert alert-success mt-3">
                            <h5><i class="fas fa-info-circle"></i> ব্যাংকে জমা দেয়ার নির্দেশনা:</h5>
                            <p>উপরের বকেয়া ফি টাকা ব্যাংকে জমা দিন, ব্যাংক রসিদে আপনার নাম, শ্রেণি ও ফোন নম্বর উল্লেখ করুন, ব্যাংক জমার পর রসিদ সংরক্ষণ করুন</p>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div class="alert alert-info mb-4" style="border: 2px dashed #006747; border-radius: 10px; background-color: #f8fff7; display: none;">
                    <h5 class="text-center" style="color: #006747; font-weight: bold; margin-top: 10px;"><?php echo htmlspecialchars($site_name); ?></h5>
                    <p class="text-center" style="margin-top: -5px;"><?php echo htmlspecialchars($site_address); ?></p>
                    <div class="text-center" style="border-top: 1px solid #006747; margin: 15px 0; padding-top: 10px;">
                        <p class="mb-0" style="font-weight: 500;">
                            আপনার সেশন চার্জ, বেতন ও এডমিশন ফি বাবদ (ক্লাস 
                            <strong><?php echo htmlspecialchars($application['class_name'] . ($application['section'] ? ' - ' . $application['section'] : '')); ?></strong>
                            এর জন্য নির্ধারিত যে সেশন চার্জ থাকবে তা যুক্ত হবে) টাকা জমা করে তোমার ভর্তি কনফার্ম কর।
                        </p>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Personal Information Section -->
                <h4 class="section-title"><i class="fas fa-user"></i> ব্যক্তিগত তথ্য</h4>
                
                <div class="row">
                    <div class="col-md-4">
                        <div class="info-row">
                            <span class="info-label">নাম:</span>
                            <span><?php echo htmlspecialchars($application['first_name'] . ' ' . $application['last_name']); ?></span>
                        </div>
                        
                        <div class="info-row">
                            <span class="info-label">পিতার নাম:</span>
                            <span><?php echo htmlspecialchars($application['father_name']); ?></span>
                        </div>
                        
                        <div class="info-row">
                            <span class="info-label">মাতার নাম:</span>
                            <span><?php echo htmlspecialchars($application['mother_name']); ?></span>
                        </div>
                        
                        <div class="info-row">
                            <span class="info-label">জন্ম তারিখ:</span>
                            <span><?php echo date('d/m/Y', strtotime($application['date_of_birth'])); ?></span>
                        </div>
                        
                        <div class="info-row">
                            <span class="info-label">ধর্ম:</span>
                            <span>
                                <?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 'N/A';
                                    }
                                ?>
                            </span>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="info-row">
                            <span class="info-label">লিঙ্গ:</span>
                            <span>
                                <?php 
                                    echo ($application['gender'] == 'male') ? 'পুরুষ' : 
                                        (($application['gender'] == 'female') ? 'মহিলা' : 'অন্যান্য'); 
                                ?>
                            </span>
                        </div>
                        
                        <div class="info-row">
                            <span class="info-label">ছাত্র/ছাত্রীর ফোন:</span>
                            <span><?php echo htmlspecialchars($application['phone']); ?></span>
                        </div>
                        
                        <div class="info-row">
                            <span class="info-label">পিতা/অভিভাবকের ফোন:</span>
                            <span><?php echo htmlspecialchars($application['father_phone'] ?? 'N/A'); ?></span>
                        </div>
                        
                        <div class="info-row">
                            <span class="info-label">ইমেইল:</span>
                            <span><?php echo htmlspecialchars($application['email'] ?? 'N/A'); ?></span>
                        </div>
                        
                        <?php if (!empty($application['present_address'])): ?>
                            <div class="info-row">
                                <span class="info-label">ঠিকানা:</span>
                                <span><?php echo htmlspecialchars($application['present_address']); ?></span>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="col-md-4 text-center">
                        <!-- Student Photo -->
                        <?php if (!empty($application['photo_path'])): ?>
                        <div class="info-row">
                            <span class="info-label">ছাত্র/ছাত্রীর ছবি:</span>
                        </div>
                        <div style="display: flex; justify-content: center; margin-top: 10px;">
                            <img src="<?php echo (!preg_match('/^https?:\/\//', $application['photo_path'])) ? '.' . htmlspecialchars($application['photo_path']) : htmlspecialchars($application['photo_path']); ?>" alt="Student Photo" class="student-photo" style="max-width: 120px; max-height: 150px; border: 2px solid #006747; border-radius: 5px;" onerror="this.onerror=null; this.parentElement.parentElement.innerHTML='<i class=&quot;fas fa-user-circle student-photo&quot; style=&quot;font-size: 50px; color: #ccc;&quot;></i>';">
                        </div>
                    <?php else: ?>
                        <div class="info-row">
                            <span class="info-label">ছাত্র/ছাত্রীর ছবি:</span>
                        </div>
                        <div style="display: flex; justify-content: center; margin-top: 10px;">
                            <i class="fas fa-user-circle student-photo" style="font-size: 50px; color: #ccc;"></i>
                        </div>
                    <?php endif; ?>
                    </div>
                </div>
                
                <!-- Academic Information Section -->
                <h4 class="section-title mt-4"><i class="fas fa-graduation-cap"></i> শিক্ষাগত তথ্য</h4>
                
                <div class="row">
                    <div class="col-md-6">
                        <div class="info-row">
                            <span class="info-label">আবেদন করা ক্লাস:</span>
                            <span><?php echo htmlspecialchars($application['class_name'] . ($application['section'] ? ' - ' . $application['section'] : '')); ?></span>
                        </div>
                        
                        <?php if (!empty($application['applying_for_session'])): ?>
                            <div class="info-row">
                                <span class="info-label">সেশন:</span>
                                <span><?php echo htmlspecialchars($application['applying_for_session']); ?></span>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($application['applying_for_group'])): ?>
                            <div class="info-row">
                                <span class="info-label">গ্রুপ:</span>
                                <span><?php echo htmlspecialchars($application['applying_for_group']); ?></span>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="col-md-6">
                        <?php if (!empty($application['previous_class']) || !empty($application['previous_school'])): ?>
                            <div class="info-row">
                                <span class="info-label">পূর্ববর্তী শিক্ষা:</span>
                                <span>
                                    <?php 
                                        echo htmlspecialchars($application['previous_class'] ?? '');
                                        if (!empty($application['previous_school'])) {
                                            echo ' - ' . htmlspecialchars($application['previous_school']);
                                        }
                                    ?>
                                </span>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($application['selected_subjects'])): ?>
                            <?php 
                                $selected_subjects = json_decode($application['selected_subjects'], true);
                                if (is_array($selected_subjects) && !empty($selected_subjects)) {
                                    // Get subject names from database
                                    $placeholders = str_repeat('?,', count($selected_subjects) - 1) . '?';
                                    $stmt = $pdo->prepare("SELECT name FROM subjects WHERE id IN ($placeholders) AND status = 'active'");
                                    $stmt->execute($selected_subjects);
                                    $subject_names = $stmt->fetchAll(PDO::FETCH_COLUMN);
                                }
                            ?>
                            <div class="info-row">
                                <span class="info-label">নির্বাচিত বিষয়সমূহ:</span>
                                <span>
                                    <?php 
                                        if (!empty($subject_names)) {
                                            echo htmlspecialchars(implode(', ', $subject_names));
                                        } else {
                                            echo 'বিষয় তথ্য পাওয়া যায়নি';
                                        }
                                    ?>
                                </span>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Footer Note -->
                <div class="alert alert-info mt-4">
                    <i class="fas fa-info-circle"></i> 
                    <strong>দ্রষ্টব্য:</strong>  এই অনলাইন ভর্তি আবেদন ফরমটি সংরক্ষণ করুন। ভর্তি সংক্রান্ত যেকোনো তথ্যের জন্য এই আবেদন নং ব্যবহার করা হবে।<br>
                    <strong>গুরুত্বপূর্ণ:</strong> আপনার সেশন চার্জ, বেতন ও এডমিশন ফি বাবদ (ক্লাস 
                    <strong><?php echo htmlspecialchars($application['class_name'] . ($application['section'] ? ' - ' . $application['section'] : '')); ?></strong>
                    এর জন্য নির্ধারিত যে সেশন চার্জ থাকবে তা যুক্ত হবে) টাকা জমা করে তোমার ভর্তি কনফার্ম কর।
                </div>
            </div>
        </div>
    </div>

    <script>
        // Auto print when page loads
        window.addEventListener('DOMContentLoaded', function() {
            window.print();
        });
    </script>
    <style>
        @media print {
            .no-print {
                display: none;
            }
            .receipt-header {
                display: none;
            }
        }
    </style>
</body>
</html>