<?php
session_start();

// Handle clear logo request
if (isset($_GET['clear_logo']) && $_GET['clear_logo'] == '1') {
    unset($_SESSION['custom_logo_path']);
    // Redirect to clean URL
    $redirect_url = '?';
    $params = [];
    if (isset($_GET['session']) && !empty($_GET['session'])) $params[] = 'session=' . urlencode($_GET['session']);
    if (isset($_GET['class_id']) && !empty($_GET['class_id'])) $params[] = 'class_id=' . $_GET['class_id'];
    if (isset($_GET['group_name']) && !empty($_GET['group_name'])) $params[] = 'group_name=' . urlencode($_GET['group_name']);
    if (!empty($params)) $redirect_url .= implode('&', $params);
    header('Location: ' . $redirect_url);
    exit();
}

require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

// Only admin and teachers can access this page
if ($user_role != 'admin' && $user_role != 'teacher') {
    header('Location: ../index.php');
    exit();
}

// Get filter parameters
$session_filter = isset($_GET['session']) ? $_GET['session'] : '';
$class_filter = isset($_GET['class_id']) ? intval($_GET['class_id']) : 0;
$group_filter = isset($_GET['group_name']) ? $_GET['group_name'] : '';

// Get student data if ID is provided
$student = null;
$student_id = isset($_GET['student_id']) ? intval($_GET['student_id']) : 0;

if ($student_id > 0) {
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
}

// Handle form submission for customizing certificate
$certificate_title = "মেধা প্রত্যয়ন পত্র";
$certificate_content = "এই মর্মে প্রত্যয়ন করা যাইতেছে যে, তিনি এ প্রতিষ্ঠানের ছাত্র/ছাত্রী হিসাবে নমুনাকৃত আচরণ, শৃংখলা ও শিক্ষার প্রতি আগ্রহ প্রকাশ করিয়াছেন। তিনি পড়াশোনায় অত্যন্ত মেধাবী এবং পরীক্ষায় উত্তম ফলাফল অর্জন করেছেন।";
$additional_wishes = "আমি তার সার্বিক মঙ্গল কামনা করি।";
$signature_title = "প্রধান শিক্ষক";
$signature_name = "প্রধান শিক্ষক";
$organization_name = "কুড়ুলগাছি মাধ্যমিক বিদ্যালয়";
$organization_address = "কুড়ুলগাছি, কাপাসিয়া, চট্টগ্রাম";
$certificate_date = date('d/m/Y');

// Get site settings for logo
$settings = [];
if (function_exists('get_all_settings')) {
    $settings = get_all_settings($pdo);
    $organization_name = $settings['site_name'] ?? $organization_name;
    $organization_address = $settings['address'] ?? $organization_address;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $certificate_title = $_POST['certificate_title'] ?? $certificate_title;
    $certificate_content = $_POST['certificate_content'] ?? $certificate_content;
    $additional_wishes = $_POST['additional_wishes'] ?? $additional_wishes;
    $signature_title = $_POST['signature_title'] ?? $signature_title;
    $signature_name = $_POST['signature_name'] ?? $signature_name;
    $organization_name = $_POST['organization_name'] ?? $organization_name;
    $organization_address = $_POST['organization_address'] ?? $organization_address;
    $certificate_date = $_POST['certificate_date'] ?? $certificate_date;
    $student_id = intval($_POST['student_id']);
    
    // Handle custom logo upload if provided
    if (isset($_FILES['custom_logo']) && $_FILES['custom_logo']['error'] == 0) {
        $upload_dir = '../uploads/logos/';
        
        // Create directory if it doesn't exist
        if (!file_exists($upload_dir)) {
            if (!mkdir($upload_dir, 0755, true)) {
                // Handle directory creation failure
                error_log("Failed to create upload directory: " . $upload_dir);
            }
        }
        
        // Check file extension instead of mime_content_type for better compatibility
        $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
        $file_extension = strtolower(pathinfo($_FILES['custom_logo']['name'], PATHINFO_EXTENSION));
        
        if (in_array($file_extension, $allowed_extensions)) {
            $new_filename = 'custom_logo_' . time() . '_' . uniqid() . '.' . $file_extension;
            $upload_path = $upload_dir . $new_filename;
            
            if (move_uploaded_file($_FILES['custom_logo']['tmp_name'], $upload_path)) {
                $custom_logo_path = $upload_path;
                // Store in session for persistence
                $_SESSION['custom_logo_path'] = $custom_logo_path;
            } else {
                // Handle upload failure
                error_log("Failed to move uploaded file to: " . $upload_path);
            }
        } else {
            // Handle invalid file type
            error_log("Invalid file extension: " . $file_extension);
        }
    } else {
        // Use existing custom logo if no new upload
        $custom_logo_path = isset($_POST['existing_custom_logo']) ? $_POST['existing_custom_logo'] : null;
        if ($custom_logo_path) {
            $_SESSION['custom_logo_path'] = $custom_logo_path;
        }
    }
    
    // Get updated student data
    $stmt = $pdo->prepare("SELECT * FROM students WHERE id = ?");
    $stmt->execute([$student_id]);
    $student = $stmt->fetch();
    
    // Get custom values if provided
    $custom_student_name = $_POST['custom_student_name'] ?? '';
    $custom_father_name = $_POST['custom_father_name'] ?? '';
    $custom_mother_name = $_POST['custom_mother_name'] ?? '';
    $custom_class = $_POST['custom_class'] ?? '';
    $custom_roll = $_POST['custom_roll'] ?? '';
        
    // Get logo display preference
    $show_logo = $_POST['show_logo'] ?? 'yes';
}

// Get custom logo from session if available
$custom_logo_path = $_SESSION['custom_logo_path'] ?? null;
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>মেধা প্রত্যয়ন পত্র - স্কুল ম্যানেজমেন্ট সিস্টেম</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&display=swap" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Hind Siliguri', sans-serif;
        }
        
        .certificate-container {
            max-width: 900px;
            margin: 30px auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 0 30px rgba(0,0,0,0.1);
            padding: 30px;
            font-family: 'Hind Siliguri', sans-serif;
        }
        
        .certificate-preview {
            background: #fce4ec;
            border: 2px solid #e91e63;
            border-radius: 10px;
            padding: 40px;
            margin: 30px 0;
            position: relative;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="%23fce4ec"/><polygon points="50,20 55,35 70,35 58,45 63,60 50,50 37,60 42,45 30,35 45,35" fill="%23e91e63" opacity="0.1"/></svg>');
            background-size: 100px 100px;
            font-family: 'Hind Siliguri', sans-serif;
        }
        
        .certificate-header {
            text-align: center;
            margin-bottom: 30px;
            position: relative;
        }
        
        .institution-logo {
            position: absolute;
            top: 0;
            left: 0;
            width: 80px;
            height: 80px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #f8f9fa;
            border-radius: 50%;
            border: 2px solid #e91e63;
        }
        
        .institution-info {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .institution-name {
            font-size: 1.8rem;
            font-weight: bold;
            color: #880e4f;
            margin-bottom: 5px;
        }
        
        .institution-address {
            font-size: 1.2rem;
            color: #666;
            margin-bottom: 15px;
        }
        
        .certificate-title {
            font-size: 2.5rem;
            font-weight: bold;
            color: #880e4f;
            margin-bottom: 10px;
            text-decoration: underline;
        }
        
        .certificate-content {
            font-size: 1.2rem;
            line-height: 1.8;
            text-align: justify;
            margin: 30px 0;
            min-height: 200px;
        }
        
        .additional-wishes {
            font-size: 1.2rem;
            line-height: 1.8;
            text-align: justify;
            margin: 20px 0 40px 0;
            font-style: italic;
        }
        
        .signature-section {
            margin-top: 60px;
            display: flex;
            justify-content: flex-end;
        }
        
        .signature-box {
            text-align: center;
            margin-right: 50px;
        }
        
        .signature-line {
            width: 200px;
            height: 1px;
            background: #333;
            margin: 0 auto 10px;
        }
        
        .student-info {
            background: #e8f4f8;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .form-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 30px;
            font-family: 'Hind Siliguri', sans-serif;
        }
        
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            opacity: 0.05;
            font-size: 10rem;
            font-weight: bold;
            color: #880e4f;
            pointer-events: none;
            z-index: 0;
        }
        
        .print-btn {
            background: linear-gradient(135deg, #e91e63 0%, #880e4f 100%);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            font-size: 1.1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            font-family: 'Hind Siliguri', sans-serif;
        }
        
        .print-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            
            .certificate-container {
                box-shadow: none;
                margin: 0;
                padding: 20px;
            }
            
            .certificate-preview {
                border: none;
                box-shadow: none;
            }
            
            .institution-logo {
                position: static;
                margin: 0 auto 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="certificate-container">
            <!-- Header with back button -->
            <div class="d-flex justify-content-between align-items-center no-print mb-4">
                <h2><i class="fas fa-award text-danger me-2"></i>মেধা প্রত্যয়ন পত্র তৈরি</h2>
                <a href="../index.php" class="btn btn-secondary">
                    <i class="fas fa-arrow-left me-1"></i>ড্যাশবোর্ডে ফিরে যান
                </a>
            </div>
            
            <?php if (!$student): ?>
                <!-- Student Selection Form with Filters -->
                <div class="form-section no-print">
                    <h4 class="mb-4"><i class="fas fa-user-graduate me-2"></i>ছাত্র/ছাত্রী নির্বাচন করুন</h4>
                    
                    <!-- Filter Form -->
                    <form method="GET" action="" class="mb-4">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="session" class="form-label">সেশন</label>
                                    <select name="session" id="session" class="form-select">
                                        <option value="">সব সেশন</option>
                                        <?php
                                        $stmt = $pdo->query("SELECT DISTINCT session FROM students WHERE session IS NOT NULL AND session != '' ORDER BY session DESC");
                                        while ($row = $stmt->fetch()) {
                                            $selected = ($session_filter == $row['session']) ? 'selected' : '';
                                            echo "<option value='{$row['session']}' {$selected}>{$row['session']}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="class_id" class="form-label">ক্লাস</label>
                                    <select name="class_id" id="class_id" class="form-select">
                                        <option value="">সব ক্লাস</option>
                                        <?php
                                        $stmt = $pdo->query("SELECT id, name FROM classes ORDER BY name");
                                        while ($row = $stmt->fetch()) {
                                            $selected = ($class_filter == $row['id']) ? 'selected' : '';
                                            echo "<option value='{$row['id']}' {$selected}>{$row['name']}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="group_name" class="form-label">গ্রুপ</label>
                                    <select name="group_name" id="group_name" class="form-select">
                                        <option value="">সব গ্রুপ</option>
                                        <?php
                                        $stmt = $pdo->query("SELECT DISTINCT group_name FROM students WHERE group_name IS NOT NULL AND group_name != '' ORDER BY group_name");
                                        while ($row = $stmt->fetch()) {
                                            $selected = ($group_filter == $row['group_name']) ? 'selected' : '';
                                            echo "<option value='{$row['group_name']}' {$selected}>{$row['group_name']}</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-end">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-filter me-1"></i>ফিল্টার করুন
                            </button>
                            <a href="" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i>রিসেট
                            </a>
                        </div>
                    </form>
                    
                    <!-- Student Selection -->
                    <form method="GET" action="">
                        <!-- Pass filter parameters -->
                        <?php if ($session_filter): ?>
                            <input type="hidden" name="session" value="<?php echo htmlspecialchars($session_filter); ?>">
                        <?php endif; ?>
                        <?php if ($class_filter): ?>
                            <input type="hidden" name="class_id" value="<?php echo $class_filter; ?>">
                        <?php endif; ?>
                        <?php if ($group_filter): ?>
                            <input type="hidden" name="group_name" value="<?php echo htmlspecialchars($group_filter); ?>">
                        <?php endif; ?>
                        
                        <div class="row">
                            <div class="col-md-10">
                                <div class="mb-3">
                                    <label for="student_id" class="form-label">ছাত্র/ছাত্রী নির্বাচন করুন</label>
                                    <select name="student_id" id="student_id" class="form-select" required>
                                        <option value="">নির্বাচন করুন...</option>
                                        <?php
                                        // Build query with filters
                                        $query = "SELECT s.id, s.first_name, s.last_name, c.name as class_name, s.roll_number 
                                                 FROM students s 
                                                 LEFT JOIN classes c ON s.class_id = c.id 
                                                 WHERE s.status = 'active'";
                                        $params = [];
                                        
                                        if ($session_filter) {
                                            $query .= " AND s.session = ?";
                                            $params[] = $session_filter;
                                        }
                                        
                                        if ($class_filter) {
                                            $query .= " AND s.class_id = ?";
                                            $params[] = $class_filter;
                                        }
                                        
                                        if ($group_filter) {
                                            $query .= " AND s.group_name = ?";
                                            $params[] = $group_filter;
                                        }
                                        
                                        $query .= " ORDER BY c.name, s.roll_number";
                                        
                                        $stmt = $pdo->prepare($query);
                                        $stmt->execute($params);
                                        
                                        while ($row = $stmt->fetch()) {
                                            echo "<option value='{$row['id']}'>{$row['first_name']} {$row['last_name']} (ক্লাস: {$row['class_name']}, রোল: {$row['roll_number']})</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="mb-3">
                                    <label class="form-label">&nbsp;</label>
                                    <div>
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="fas fa-arrow-right me-1"></i>পরবর্তী
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                
                <div class="text-center text-muted mt-5">
                    <i class="fas fa-info-circle fa-3x mb-3"></i>
                    <p>মেধা প্রত্যয়ন পত্র তৈরি করতে প্রথমে একজন ছাত্র/ছাত্রী নির্বাচন করুন</p>
                </div>
            <?php else: ?>
                <!-- Certificate Customization Form -->
                <div class="form-section no-print">
                    <h4 class="mb-4"><i class="fas fa-edit me-2"></i>মেধা প্রত্যয়ন পত্র কাস্টমাইজ করুন</h4>
                    <form method="POST" action="" enctype="multipart/form-data">
                        <input type="hidden" name="student_id" value="<?php echo $student['id']; ?>">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="certificate_title" class="form-label">প্রত্যয়ন পত্রের শিরোনাম</label>
                                    <input type="text" class="form-control" id="certificate_title" name="certificate_title" 
                                           value="<?php echo htmlspecialchars($certificate_title); ?>" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="certificate_content" class="form-label">প্রত্যয়ন পত্রের বিবরণ</label>
                                    <textarea class="form-control" id="certificate_content" name="certificate_content" 
                                              rows="5" required><?php echo htmlspecialchars($certificate_content); ?></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="additional_wishes" class="form-label">অতিরিক্ত কামনা/বার্তা</label>
                                    <textarea class="form-control" id="additional_wishes" name="additional_wishes" 
                                              rows="3"><?php echo htmlspecialchars($additional_wishes); ?></textarea>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="certificate_date" class="form-label">তারিখ</label>
                                    <input type="text" class="form-control" id="certificate_date" name="certificate_date" 
                                           value="<?php echo htmlspecialchars($certificate_date); ?>" required>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                    <label for="organization_name" class="form-label">প্রতিষ্ঠানের নাম</label>
                                    <input type="text" class="form-control" id="organization_name" name="organization_name" 
                                           value="<?php echo htmlspecialchars($organization_name); ?>" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="organization_address" class="form-label">প্রতিষ্ঠানের ঠিকানা</label>
                                    <input type="text" class="form-control" id="organization_address" name="organization_address" 
                                           value="<?php echo htmlspecialchars($organization_address); ?>" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="signature_title" class="form-label">স্বাক্ষরকারীর পদবী</label>
                                    <input type="text" class="form-control" id="signature_title" name="signature_title" 
                                           value="<?php echo htmlspecialchars($signature_title); ?>" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="signature_name" class="form-label">স্বাক্ষরকারীর নাম</label>
                                    <input type="text" class="form-control" id="signature_name" name="signature_name" 
                                           value="<?php echo htmlspecialchars($signature_name); ?>" required>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="custom_student_name" class="form-label">ছাত্র/ছাত্রীর নাম (বাংলায়)</label>
                                    <input type="text" class="form-control" id="custom_student_name" name="custom_student_name" 
                                           value="<?php echo htmlspecialchars($student['first_name'] . ' ' . $student['last_name']); ?>">
                                    <div class="form-text">ডিফল্ট হিসাবে ডাটাবেসের নাম ব্যবহার হবে যদি খালি থাকে</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="custom_father_name" class="form-label">পিতার নাম (বাংলায়)</label>
                                    <input type="text" class="form-control" id="custom_father_name" name="custom_father_name" 
                                           value="<?php echo htmlspecialchars($student['father_name']); ?>">
                                    <div class="form-text">ডিফল্ট হিসাবে ডাটাবেসের নাম ব্যবহার হবে যদি খালি থাকে</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="custom_mother_name" class="form-label">মাতার নাম (বাংলায়)</label>
                                    <input type="text" class="form-control" id="custom_mother_name" name="custom_mother_name" 
                                           value="<?php echo htmlspecialchars($student['mother_name']); ?>">
                                    <div class="form-text">ডিফল্ট হিসাবে ডাটাবেসের নাম ব্যবহার হবে যদি খালি থাকে</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="custom_class" class="form-label">ক্লাস (বাংলায়)</label>
                                    <input type="text" class="form-control" id="custom_class" name="custom_class" 
                                           value="<?php echo $classData ? htmlspecialchars($classData['name']) : ''; ?>">
                                    <div class="form-text">ডিফল্ট হিসাবে ডাটাবেসের ক্লাস ব্যবহার হবে যদি খালি থাকে</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="custom_roll" class="form-label">রোল (বাংলায়)</label>
                                    <input type="text" class="form-control" id="custom_roll" name="custom_roll" 
                                           value="<?php echo htmlspecialchars($student['roll_number']); ?>">
                                    <div class="form-text">ডিফল্ট হিসাবে ডাটাবেসের রোল ব্যবহার হবে যদি খালি থাকে</div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">প্রতিষ্ঠানের লোগো প্রদর্শন</label>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="show_logo" id="show_logo_yes" value="yes" <?php echo ($show_logo ?? 'yes') === 'yes' ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="show_logo_yes">দেখাবে</label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="radio" name="show_logo" id="show_logo_no" value="no" <?php echo ($show_logo ?? 'yes') === 'no' ? 'checked' : ''; ?>>
                                        <label class="form-check-label" for="show_logo_no">লুকাবে</label>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="custom_logo" class="form-label">কাস্টম লোগো আপলোড করুন</label>
                                    <input type="file" class="form-control" id="custom_logo" name="custom_logo" accept="image/*">
                                    <div class="form-text">সাপোর্টেড ফরম্যাট: JPG, PNG, GIF, WebP</div>
                                    <?php if (isset($custom_logo_path) && !empty($custom_logo_path) && file_exists(substr($custom_logo_path, 3))): ?>
                                        <div class="mt-2 alert alert-info">
                                            <label class="form-label">বর্তমান কাস্টম লোগো:</label><br>
                                            <img src="<?php echo $custom_logo_path; ?>" alt="Current Custom Logo" style="max-height: 80px; max-width: 80px; object-fit: contain;"><br>
                                            <small class="text-muted">কাস্টম লোগো সক্রিয় আছে</small>
                                            <input type="hidden" name="existing_custom_logo" value="<?php echo htmlspecialchars($custom_logo_path); ?>">
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-center">
                            <button type="submit" class="btn btn-success">
                                <i class="fas fa-sync-alt me-1"></i>আপডেট করুন
                            </button>
                            <button type="button" class="print-btn" onclick="window.print()">
                                <i class="fas fa-print me-1"></i>প্রিন্ট করুন
                            </button>
                            <?php if (isset($_SESSION['custom_logo_path']) && !empty($_SESSION['custom_logo_path'])): ?>
                                <a href="?clear_logo=1&<?php 
                                    $params = [];
                                    if ($session_filter) $params[] = 'session=' . urlencode($session_filter);
                                    if ($class_filter) $params[] = 'class_id=' . $class_filter;
                                    if ($group_filter) $params[] = 'group_name=' . urlencode($group_filter);
                                    echo implode('&', $params);
                                ?>" class="btn btn-warning ms-2">
                                    <i class="fas fa-trash me-1"></i>কাস্টম লোগো মুছুন
                                </a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
                
                <!-- Student Info -->
                <div class="student-info no-print">
                    <div class="row">
                        <div class="col-md-3">
                            <strong>নাম:</strong> <?php 
                                $display_student_name = !empty($custom_student_name) ? $custom_student_name : ($student['first_name'] . ' ' . $student['last_name']);
                                echo htmlspecialchars($display_student_name); 
                            ?>
                        </div>
                        <div class="col-md-2">
                            <strong>ক্লাস:</strong> 
                            <?php
                            $display_class = !empty($custom_class) ? $custom_class : '';
                            if (!empty($display_class)) {
                                echo htmlspecialchars($display_class);
                            } else {
                                $classStmt = $pdo->prepare("SELECT name FROM classes WHERE id = ?");
                                $classStmt->execute([$student['class_id']]);
                                $classData = $classStmt->fetch();
                                echo $classData ? htmlspecialchars($classData['name']) : 'N/A';
                            }
                            ?>
                        </div>
                        <div class="col-md-2">
                            <strong>রোল:</strong> <?php 
                                $display_roll = !empty($custom_roll) ? $custom_roll : $student['roll_number'];
                                echo htmlspecialchars($display_roll); 
                            ?>
                        </div>
                        <div class="col-md-3">
                            <strong>পিতার নাম:</strong> <?php 
                                $display_father_name = !empty($custom_father_name) ? $custom_father_name : $student['father_name'];
                                echo htmlspecialchars($display_father_name); 
                            ?>
                        </div>
                        <div class="col-md-2">
                            <strong>লিঙ্গ:</strong> <?php echo $student['gender'] == 'male' ? 'পুরুষ' : 'মহিলা'; ?>
                        </div>
                    </div>
                    <div class="row mt-2">
                        <div class="col-md-3">
                            <strong>সেশন:</strong> <?php echo htmlspecialchars($student['session']); ?>
                        </div>
                        <div class="col-md-3">
                            <strong>গ্রুপ:</strong> <?php echo htmlspecialchars($student['group_name']); ?>
                        </div>
                        <div class="col-md-3">
                            <strong>মাতার নাম:</strong> <?php 
                                $display_mother_name = !empty($custom_mother_name) ? $custom_mother_name : $student['mother_name'];
                                echo htmlspecialchars($display_mother_name); 
                            ?>
                        </div>
                    </div>
                </div>
                
                <!-- Certificate Preview -->
                <div class="certificate-preview">
                    <div class="watermark">মেধা প্রত্যয়ন</div>
                    
                    <div class="certificate-header">
                        <div class="d-flex justify-content-between align-items-start">
                            <!-- Institution Logo on Left -->
                            <div class="institution-logo">
                                <?php 
                                $logo_image = $settings['logo_image'] ?? null;
                                $show_logo = isset($_POST['show_logo']) ? $_POST['show_logo'] : 'yes'; // Default to showing logo
                                
                                // Use custom logo if uploaded, otherwise use site logo
                                $use_logo_path = null;
                                
                                // Check for custom logo first
                                if (isset($custom_logo_path) && !empty($custom_logo_path)) {
                                    // The custom logo path is relative to the root, so we need ../ to go up from certificates/
                                    $custom_logo_full_path = '../' . $custom_logo_path;
                                    if (file_exists($custom_logo_full_path)) {
                                        $use_logo_path = $custom_logo_full_path;
                                    }
                                }
                                
                                // Fallback to site logo if custom logo doesn't exist
                                if (!$use_logo_path && $logo_image) {
                                    $site_logo_full_path = '../' . $logo_image;
                                    if (file_exists($site_logo_full_path)) {
                                        $use_logo_path = $site_logo_full_path;
                                    }
                                }
                                
                                if ($show_logo === 'yes' && $use_logo_path): 
                                ?>
                                    <img src="<?php echo htmlspecialchars($use_logo_path); ?>" alt="Institution Logo" class="img-fluid" style="max-height: 80px; max-width: 80px; object-fit: contain;">
                                <?php elseif ($show_logo === 'yes'): ?>
                                    <i class="fas fa-award fa-2x text-danger"></i>
                                <?php else: ?>
                                    <div style="width: 80px; height: 80px;"></div> <!-- Empty space when logo is disabled -->
                                <?php endif; ?>
                            </div>
                            
                            <!-- Institution Info Center -->
                            <div class="institution-info text-center flex-grow-1">
                                <div class="institution-name"><?php echo htmlspecialchars($organization_name); ?></div>
                                <div class="institution-address"><?php echo htmlspecialchars($organization_address); ?></div>
                                <h1 class="certificate-title"><?php echo htmlspecialchars($certificate_title); ?></h1>
                            </div>
                            
                            <!-- Student Photo on Right -->
                            <div class="student-photo">
                                <?php if ($student && !empty($student['photo'])): ?>
                                    <img src="../<?php echo htmlspecialchars($student['photo']); ?>" alt="Student Photo" class="img-fluid" style="max-height: 80px; max-width: 60px; object-fit: cover; border: 1px solid #ccc; border-radius: 4px;">
                                <?php else: ?>
                                    <div class="no-photo" style="width: 60px; height: 80px; border: 1px solid #ccc; border-radius: 4px; display: flex; align-items: center; justify-content: center; background: #f8f9fa;">
                                        <i class="fas fa-user text-muted"></i>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="text-center mb-4">
                        <div style="border-bottom: 1px solid #333; width: 100px; margin: 0 auto;"></div>
                    </div>
                    
                    <div class="certificate-content">
                        <p>
                            এই মর্মে প্রত্যয়ন করা যাইতেছে যে, 
                            <strong><?php 
                                // Use custom name if provided, otherwise use database value
                                $display_student_name = !empty($custom_student_name) ? $custom_student_name : ($student['first_name'] . ' ' . $student['last_name']);
                                echo htmlspecialchars($display_student_name); 
                            ?></strong> 
                            পিতা: <?php 
                                $display_father_name = !empty($custom_father_name) ? $custom_father_name : $student['father_name'];
                                echo htmlspecialchars($display_father_name); 
                            ?>, 
                            মাতা: <?php 
                                $display_mother_name = !empty($custom_mother_name) ? $custom_mother_name : $student['mother_name'];
                                echo htmlspecialchars($display_mother_name); 
                            ?>,
                            ক্লাস: <?php 
                                $display_class = !empty($custom_class) ? $custom_class : ($classData ? $classData['name'] : 'N/A');
                                echo htmlspecialchars($display_class); 
                            ?>, 
                            রোল: <?php 
                                $display_roll = !empty($custom_roll) ? $custom_roll : $student['roll_number'];
                                echo htmlspecialchars($display_roll); 
                            ?> 
                            <?php echo htmlspecialchars($certificate_content); ?>
                        </p>
                    </div>
                    
                    <div class="additional-wishes">
                        <p><?php echo htmlspecialchars($additional_wishes); ?></p>
                    </div>
                    
                    <div class="signature-section">
                        <div class="signature-box">
                            <div class="signature-line"></div>
                            <div><?php echo htmlspecialchars($signature_title); ?></div>
                            <div><?php echo htmlspecialchars($signature_name); ?></div>
                            <div><?php echo htmlspecialchars($certificate_date); ?></div>
                        </div>
                    </div>
                </div>
                
                <div class="text-center no-print">
                    <button class="print-btn" onclick="window.print()">
                        <i class="fas fa-print me-1"></i>প্রিন্ট করুন
                    </button>
                    <a href="?<?php 
                        $params = [];
                        if ($session_filter) $params[] = 'session=' . urlencode($session_filter);
                        if ($class_filter) $params[] = 'class_id=' . $class_filter;
                        if ($group_filter) $params[] = 'group_name=' . urlencode($group_filter);
                        echo implode('&', $params);
                    ?>" class="btn btn-secondary ms-2">
                        <i class="fas fa-redo me-1"></i>রিসেট
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>