<?php
session_start();

// Include access control functions
require_once '../includes/access_control.php';
require_once '../config/database.php';
require_once '../includes/sidebar_layout.php';

// Check if user is logged in and has appropriate role (admin or teacher)
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

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

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

// Get filters from GET 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;
}

// Get class data if class_id is provided
$classData = null;
if ($class_filter > 0) {
    $stmt = $pdo->prepare("SELECT * FROM classes WHERE id = ?");
    $stmt->execute([$class_filter]);
    $classData = $stmt->fetch();
}

// Handle POST requests for customization
$custom_student_name = '';
$custom_father_name = '';
$custom_mother_name = '';
$custom_class = '';
$custom_roll = '';
$border_style = 'classic'; // Default border style
$show_logo = 'yes';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['activate_logo'])) {
        // Handle logo activation
        $logo_path = $_POST['activate_logo'];
        $_SESSION['custom_logo_path'] = $logo_path;
        echo json_encode(['success' => true, 'message' => 'Logo activated successfully']);
        exit();
    }
    
    if (isset($_POST['custom_logo'])) {
        // Handle custom logo upload
        if (isset($_FILES['custom_logo']) && $_FILES['custom_logo']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = '../uploads/logos/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = strtolower(pathinfo($_FILES['custom_logo']['name'], PATHINFO_EXTENSION));
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
            
            if (in_array($file_extension, $allowed_extensions)) {
                $filename = uniqid('logo_') . '.' . $file_extension;
                $destination = $upload_dir . $filename;
                
                if (move_uploaded_file($_FILES['custom_logo']['tmp_name'], $destination)) {
                    $relative_path = 'uploads/logos/' . $filename;
                    $_SESSION['custom_logo_path'] = $relative_path;
                    echo json_encode(['success' => true, 'logo_path' => $filename]);
                    exit();
                }
            }
        }
        echo json_encode(['success' => false, 'message' => 'Invalid file type or upload error']);
        exit();
    }
    
    if (isset($_POST['clear_custom_logo'])) {
        // Clear custom logo
        unset($_SESSION['custom_logo_path']);
        echo json_encode(['success' => true]);
        exit();
    }
    
    if (isset($_POST['show_logo'])) {
        // Toggle logo display
        echo json_encode(['success' => true]);
        exit();
    }
    
    // Handle certificate customization
    $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;
    $border_style = $_POST['border_style'] ?? $border_style;
    $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;

// Handle logo clearing
if (isset($_GET['clear_logo'])) {
    unset($_SESSION['custom_logo_path']);
    // Redirect back to the page without the clear_logo parameter
    $redirect_url = '?';
    $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);
    if ($params) $redirect_url .= implode('&', $params);
    header('Location: ' . $redirect_url);
    exit();
}
?>

<!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: #fff9e6;
            border: 2px solid #d4af37;
            border-radius: 10px;
            padding: 40px;
            margin: 30px 0;
            position: relative;
            font-family: 'Hind Siliguri', sans-serif;
        }
        
        /* Border styles */
        .border-classic {
            border: 2px solid #d4af37;
            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="%23fff9e6"/><path d="M20,20 Q40,5 50,20 T80,20 Q95,40 80,50 T80,80 Q60,95 50,80 T20,80 Q5,60 20,50 T20,20" fill="none" stroke="%23d4af37" stroke-width="0.5"/></svg>');
            background-size: 100px 100px;
        }
        
        .border-modern {
            border: 3px solid #4CAF50;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 80 80"><rect width="80" height="80" fill="%23f1f8e9"/><circle cx="20" cy="20" r="3" fill="%234CAF50" opacity="0.3"/><circle cx="60" cy="20" r="3" fill="%234CAF50" opacity="0.3"/><circle cx="20" cy="60" r="3" fill="%234CAF50" opacity="0.3"/><circle cx="60" cy="60" r="3" fill="%234CAF50" opacity="0.3"/></svg>');
            background-size: 80px 80px;
        }
        
        .border-elegant {
            border: 2px solid #9C27B0;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="120" height="120" viewBox="0 0 120 120"><rect width="120" height="120" fill="%23fafafa"/><path d="M30,30 L90,30 L90,90 L30,90 Z" fill="none" stroke="%239C27B0" stroke-width="1" opacity="0.2"/><circle cx="60" cy="60" r="25" fill="none" stroke="%239C27B0" stroke-width="1" opacity="0.1"/></svg>');
            background-size: 120px 120px;
        }
        
        .border-traditional {
            border: 3px double #8B4513;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="60" height="60" viewBox="0 0 60 60"><rect width="60" height="60" fill="%23fefefe"/><path d="M10,10 L50,10 L50,50 L10,50 Z" fill="none" stroke="%238B4513" stroke-width="0.5" opacity="0.4"/><path d="M20,20 L40,20 L40,40 L20,40 Z" fill="none" stroke="%238B4513" stroke-width="0.3" opacity="0.2"/></svg>');
            background-size: 60px 60px;
        }
        
        .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 #d4af37;
        }
        
        .institution-info {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .institution-name {
            font-size: 1.8rem;
            font-weight: bold;
            color: #8B4513;
            margin-bottom: 5px;
        }
        
        .institution-address {
            font-size: 1.2rem;
            color: #666;
            margin-bottom: 15px;
        }
        
        .certificate-title {
            font-size: 2.5rem;
            font-weight: bold;
            color: #8B4513;
            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: #8B4513;
            pointer-events: none;
            z-index: 0;
        }
        
        .print-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 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);
        }
        
        .border-option {
            cursor: pointer;
            transition: all 0.3s ease;
            border: 2px solid transparent;
        }
        
        .border-option:hover {
            transform: scale(1.05);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .border-option.selected {
            border-color: #007bff;
            box-shadow: 0 0 10px rgba(0,123,255,0.3);
        }
        
        @media print {
            /* Hide everything except the certificate */
            * {
                visibility: hidden;
            }
            
            /* Show only certificate container and its children */
            .certificate-container,
            .certificate-container *,
            .certificate-preview,
            .certificate-preview * {
                visibility: visible;
            }
            
            /* Hide all no-print elements */
            .no-print,
            .no-print *,
            .form-section,
            .form-section *,
            .student-info,
            .student-info *,
            .modal,
            .modal *,
            .navbar,
            .navbar *,
            header,
            footer,
            .btn,
            .alert,
            .notification-container {
                display: none !important;
                visibility: hidden !important;
            }
            
            /* Reset certificate container for printing */
            .certificate-container {
                position: static !important;
                box-shadow: none !important;
                margin: 0 !important;
                padding: 0 !important;
                border: none !important;
                background: white !important;
                width: 100% !important;
                max-width: 100% !important;
                page-break-inside: avoid;
            }
            
            /* Reset certificate preview for printing */
            .certificate-preview {
                box-shadow: none !important;
                margin: 0 !important;
                padding: 30px !important;
                border: 2px solid #000 !important;
                page-break-inside: avoid;
            }
            
            /* Ensure watermark prints */
            .watermark {
                visibility: visible !important;
                opacity: 0.1 !important;
            }
        }
    </style>
</head>
<body>
        <div class="container-fluid certificate-container" style="margin-top: 20px;">
            
            <h2 class="text-center mb-4">
                <i class="fas fa-certificate text-warning me-2"></i>প্রত্যয়ন পত্র
            </h2>
            
            <?php if (!$student): ?>
                <!-- Student Selection Form -->
                <div class="form-section no-print">
                    <h4 class="mb-4"><i class="fas fa-filter me-2"></i>ছাত্র/ছাত্রী নির্বাচন করুন</h4>
                    
                    <form method="GET" action="" class="mb-4">
                        <div class="row g-3">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <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="form-group">
                                    <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 * 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="form-group">
                                    <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 mt-3">
                            <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="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>নাম</th>
                                        <th>পিতার নাম</th>
                                        <th>ক্লাস</th>
                                        <th>রোল</th>
                                        <th>গ্রুপ</th>
                                        <th>অ্যাকশন</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sql = "SELECT s.*, c.name as class_name FROM students s LEFT JOIN classes c ON s.class_id = c.id WHERE 1=1";
                                    $params = [];
                                    
                                    if ($session_filter) {
                                        $sql .= " AND s.session = ?";
                                        $params[] = $session_filter;
                                    }
                                    
                                    if ($class_filter) {
                                        $sql .= " AND s.class_id = ?";
                                        $params[] = $class_filter;
                                    }
                                    
                                    if ($group_filter) {
                                        $sql .= " AND s.group_name = ?";
                                        $params[] = $group_filter;
                                    }
                                    
                                    $sql .= " ORDER BY s.first_name, s.last_name";
                                    
                                    $stmt = $pdo->prepare($sql);
                                    $stmt->execute($params);
                                    
                                    while ($row = $stmt->fetch()) {
                                        echo "<tr>";
                                        echo "<td>" . htmlspecialchars($row['first_name'] . ' ' . $row['last_name']) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['father_name']) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['class_name']) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['roll_number']) . "</td>";
                                        echo "<td>" . htmlspecialchars($row['group_name']) . "</td>";
                                        echo "<td>";
                                        echo "<a href='?student_id={$row['id']}&";
                                        $params_str = [];
                                        if ($session_filter) $params_str[] = 'session=' . urlencode($session_filter);
                                        if ($class_filter) $params_str[] = 'class_id=' . $class_filter;
                                        if ($group_filter) $params_str[] = 'group_name=' . urlencode($group_filter);
                                        echo implode('&', $params_str);
                                        echo "' class='btn btn-sm btn-primary'>নির্বাচন করুন</a>";
                                        echo "</td>";
                                        echo "</tr>";
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </form>
                </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="">
                        <div class="row g-4">
                            <!-- Organization Details -->
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header bg-primary text-white">
                                        <h5 class="mb-0"><i class="fas fa-building me-2"></i>প্রতিষ্ঠানের তথ্য</h5>
                                    </div>
                                    <div class="card-body">
                                        <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); ?>">
                                        </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); ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Certificate Details -->
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header bg-success text-white">
                                        <h5 class="mb-0"><i class="fas fa-file-alt me-2"></i>প্রত্যয়ন পত্রের বিবরণ</h5>
                                    </div>
                                    <div class="card-body">
                                        <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); ?>">
                                        </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); ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Content Customization -->
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header bg-info text-white">
                                        <h5 class="mb-0"><i class="fas fa-pen me-2"></i>বিবরণ কাস্টমাইজ</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="certificate_content" class="form-label">প্রধান বিবরণ</label>
                                                    <textarea class="form-control" id="certificate_content" name="certificate_content" rows="4"><?php echo htmlspecialchars($certificate_content); ?></textarea>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="additional_wishes" class="form-label">অতিরিক্ত শুভেচ্ছা</label>
                                                    <textarea class="form-control" id="additional_wishes" name="additional_wishes" rows="4"><?php echo htmlspecialchars($additional_wishes); ?></textarea>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Signature Details -->
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header bg-warning text-dark">
                                        <h5 class="mb-0"><i class="fas fa-signature me-2"></i>স্বাক্ষর বিবরণ</h5>
                                    </div>
                                    <div class="card-body">
                                        <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); ?>">
                                        </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); ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Border Style Selection -->
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header bg-danger text-white">
                                        <h5 class="mb-0"><i class="fas fa-border-all me-2"></i>বর্ডার ডিজাইন</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row g-2">
                                            <div class="col-6">
                                                <div class="border-option border-classic p-3 rounded text-center <?php echo ($border_style == 'classic') ? 'selected' : ''; ?>" onclick="selectBorder('classic')">
                                                    <i class="fas fa-certificate fa-2x mb-2 text-warning"></i>
                                                    <div>Classic</div>
                                                    <small class="text-muted">ক্লাসিক স্টাইল</small>
                                                    <input type="radio" name="border_style" value="classic" class="d-none" <?php echo ($border_style == 'classic') ? 'checked' : ''; ?>>
                                                </div>
                                            </div>
                                            <div class="col-6">
                                                <div class="border-option border-modern p-3 rounded text-center <?php echo ($border_style == 'modern') ? 'selected' : ''; ?>" onclick="selectBorder('modern')">
                                                    <i class="fas fa-leaf fa-2x mb-2 text-success"></i>
                                                    <div>Modern</div>
                                                    <small class="text-muted">আধুনিক স্টাইল</small>
                                                    <input type="radio" name="border_style" value="modern" class="d-none" <?php echo ($border_style == 'modern') ? 'checked' : ''; ?>>
                                                </div>
                                            </div>
                                            <div class="col-6">
                                                <div class="border-option border-elegant p-3 rounded text-center <?php echo ($border_style == 'elegant') ? 'selected' : ''; ?>" onclick="selectBorder('elegant')">
                                                    <i class="fas fa-crown fa-2x mb-2 text-purple"></i>
                                                    <div>Elegant</div>
                                                    <small class="text-muted">এলিগ্যান্ট স্টাইল</small>
                                                    <input type="radio" name="border_style" value="elegant" class="d-none" <?php echo ($border_style == 'elegant') ? 'checked' : ''; ?>>
                                                </div>
                                            </div>
                                            <div class="col-6">
                                                <div class="border-option border-traditional p-3 rounded text-center <?php echo ($border_style == 'traditional') ? 'selected' : ''; ?>" onclick="selectBorder('traditional')">
                                                    <i class="fas fa-landmark fa-2x mb-2 text-brown"></i>
                                                    <div>Traditional</div>
                                                    <small class="text-muted">প্রচলিত স্টাইল</small>
                                                    <input type="radio" name="border_style" value="traditional" class="d-none" <?php echo ($border_style == 'traditional') ? 'checked' : ''; ?>>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Custom Student Info -->
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header bg-secondary text-white">
                                        <h5 class="mb-0"><i class="fas fa-user-edit me-2"></i>ছাত্র/ছাত্রীর তথ্য কাস্টমাইজ (ঐচ্ছিক)</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <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($custom_student_name); ?>" placeholder="Leave blank to use database value">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <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($custom_father_name); ?>" placeholder="Leave blank to use database value">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <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($custom_mother_name); ?>" placeholder="Leave blank to use database value">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <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 htmlspecialchars($custom_class); ?>" placeholder="Leave blank to use database value">
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <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($custom_roll); ?>" placeholder="Leave blank to use database value">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-center mt-4">
                            <button type="submit" class="btn btn-primary btn-lg me-2">
                                <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-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-3">
                            <strong>ক্লাস:</strong> <?php 
                                $display_class = !empty($custom_class) ? $custom_class : ($classData ? $classData['name'] : 'N/A');
                                echo htmlspecialchars($display_class); 
                            ?>
                        </div>
                        <div class="col-md-3">
                            <strong>রোল:</strong> <?php 
                                $display_roll = !empty($custom_roll) ? $custom_roll : $student['roll_number'];
                                echo htmlspecialchars($display_roll); 
                            ?>
                        </div>
                    </div>
                </div>
                
                <!-- Certificate Preview -->
                <div class="certificate-preview border-<?php echo htmlspecialchars($border_style); ?>">
                    <div class="watermark"><?php echo htmlspecialchars($certificate_title); ?></div>
                    
                    <div class="certificate-header">
                        <div class="d-flex justify-content-between align-items-start">
                            <!-- Institution Logo on Left -->
                            <div class="institution-logo" id="logoContainer" style="cursor: pointer; position: relative;" title="Click to change 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; border-radius: 8px; transition: all 0.3s ease;" onmouseover="this.style.boxShadow='0 0 15px rgba(0,123,255,0.5)'; document.getElementById('logoTooltip').style.opacity='1';" onmouseout="this.style.boxShadow='none'; document.getElementById('logoTooltip').style.opacity='0';">
                                    <div style="position: absolute; bottom: -25px; left: 50%; transform: translateX(-50%); background: #007bff; color: white; padding: 3px 10px; border-radius: 15px; font-size: 12px; opacity: 0; transition: opacity 0.3s; pointer-events: none;" id="logoTooltip">Click to change logo</div>
                                <?php elseif ($show_logo === 'yes'): ?>
                                    <i class="fas fa-graduation-cap fa-2x text-warning" style="transition: all 0.3s ease;" onmouseover="this.style.transform='scale(1.2)'; this.style.textShadow='0 0 10px rgba(255,193,7,0.5)'; document.getElementById('logoTooltip').style.opacity='1';" onmouseout="this.style.transform='scale(1)'; this.style.textShadow='none'; document.getElementById('logoTooltip').style.opacity='0';"></i>
                                    <div style="position: absolute; bottom: -25px; left: 50%; transform: translateX(-50%); background: #ffc107; color: black; padding: 3px 10px; border-radius: 15px; font-size: 12px; opacity: 0; transition: opacity 0.3s; pointer-events: none;" id="logoTooltip">Click to select logo</div>
                                <?php else: ?>
                                    <div style="width: 80px; height: 80px; background: #f8f9fa; border: 2px dashed #6c757d; border-radius: 8px; display: flex; align-items: center; justify-content: center; transition: all 0.3s ease;" onmouseover="this.style.borderColor='#007bff'; this.style.backgroundColor='#e3f2fd'; document.getElementById('logoTooltip').style.opacity='1';" onmouseout="this.style.borderColor='#6c757d'; this.style.backgroundColor='#f8f9fa'; document.getElementById('logoTooltip').style.opacity='0';">
                                        <i class="fas fa-plus text-muted"></i>
                                    </div>
                                    <div style="position: absolute; bottom: -25px; left: 50%; transform: translateX(-50%); background: #6c757d; color: white; padding: 3px 10px; border-radius: 15px; font-size: 12px; opacity: 0; transition: opacity 0.3s; pointer-events: none;" id="logoTooltip">Click to select logo</div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Logo Selection Modal -->
                            <div class="modal fade" id="logoSelectionModal" tabindex="-1" aria-hidden="true">
                                <div class="modal-dialog modal-xl modal-dialog-centered">
                                    <div class="modal-content">
                                        <div class="modal-header bg-primary text-white">
                                            <h5 class="modal-title"><i class="fas fa-image me-2"></i>লোগো নির্বাচন করুন</h5>
                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                                        </div>
                                        <div class="modal-body">
                                            <div class="row">
                                                <div class="col-md-8">
                                                    <h6><i class="fas fa-th-large me-1"></i>আপনার লোগো সমূহ</h6>
                                                    <div class="row mt-3" id="logoGallery">
                                                        <div class="text-center py-5">
                                                            <div class="spinner-border text-primary" role="status">
                                                                <span class="visually-hidden">লোড হচ্ছে...</span>
                                                            </div>
                                                            <p class="mt-2">লোগো সমূহ লোড হচ্ছে...</p>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="card">
                                                        <div class="card-header">
                                                            <h6><i class="fas fa-upload me-1"></i>নতুন লোগো আপলোড করুন</h6>
                                                        </div>
                                                        <div class="card-body">
                                                            <form id="logoUploadForm" enctype="multipart/form-data">
                                                                <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>
                                                                </div>
                                                                <button type="submit" class="btn btn-primary w-100">
                                                                    <i class="fas fa-upload me-1"></i>আপলোড করুন
                                                                </button>
                                                            </form>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="card mt-3">
                                                        <div class="card-header">
                                                            <h6><i class="fas fa-cog me-1"></i>লোগো সেটিংস</h6>
                                                        </div>
                                                        <div class="card-body">
                                                            <div class="form-check form-switch mb-3">
                                                                <input class="form-check-input" type="checkbox" id="showLogoToggle" onchange="toggleLogoDisplay(this.checked)">
                                                                <label class="form-check-label" for="showLogoToggle">লোগো প্রদর্শন করুন</label>
                                                            </div>
                                                            <button class="btn btn-danger w-100" onclick="clearCustomLogo()">
                                                                <i class="fas fa-trash me-1"></i>লোগো মুছুন
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                                        </div>
                                    </div>
                                </div>
                            </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; ?>


    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Logo click functionality
        document.addEventListener('DOMContentLoaded', function() {
            const logoContainer = document.getElementById('logoContainer');
            const logoTooltip = document.getElementById('logoTooltip');
            
            if (logoContainer) {
                // Show tooltip on hover
                logoContainer.addEventListener('mouseenter', function() {
                    if (logoTooltip) {
                        logoTooltip.style.opacity = '1';
                    }
                });
                
                logoContainer.addEventListener('mouseleave', function() {
                    if (logoTooltip) {
                        logoTooltip.style.opacity = '0';
                    }
                });
                
                // Click handler to open logo selection
                logoContainer.addEventListener('click', function() {
                    // Show logo selection modal
                    showLogoSelectionModal();
                });
            }
        });
        
        function selectBorder(style) {
            // Remove selected class from all options
            document.querySelectorAll('.border-option').forEach(option => {
                option.classList.remove('selected');
            });
            
            // Add selected class to clicked option
            event.currentTarget.classList.add('selected');
            
            // Check the radio button
            event.currentTarget.querySelector('input[type="radio"]').checked = true;
        }
        
        function showLogoSelectionModal() {
            // Show existing modal
            const modalElement = document.getElementById('logoSelectionModal');
            if (modalElement) {
                const modal = new bootstrap.Modal(modalElement);
                modal.show();
                
                // Load available logos
                loadAvailableLogos();
                
                // Set initial state of toggle
                const showLogoToggle = document.getElementById('showLogoToggle');
                if (showLogoToggle) {
                    showLogoToggle.checked = <?php echo ($show_logo === 'yes' ? 'true' : 'false'); ?>;
                }
            }
        }
        
        function loadAvailableLogos() {
            // Use absolute path to avoid relative path issues
            const ajaxUrl = '../logo_gallery_ajax.php?gallery=1&t=' + Date.now();
            
            fetch(ajaxUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok: ' + response.status);
                    }
                    return response.text();
                })
                .then(html => {
                    document.getElementById('logoGallery').innerHTML = html;
                })
                .catch(error => {
                    console.error('Error loading logos:', error);
                    document.getElementById('logoGallery').innerHTML = 
                        '<div class="col-12 text-center text-danger py-5">' +
                        '<i class="fas fa-exclamation-triangle fa-2x mb-3"></i>' +
                        '<p>Failed to load logos. Error: ' + error.message + '</p>' +
                        '<button class="btn btn-primary mt-2" onclick="loadAvailableLogos()">Try Again</button>' +
                        '</div>';
                });
        }
        
        function selectLogo(logoPath, logoName) {
            // Show loading state
            const galleryElement = document.getElementById('logoGallery');
            const originalContent = galleryElement.innerHTML;
            galleryElement.innerHTML = '<div class="col-12 text-center py-5"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div><p class="mt-2">Activating logo...</p></div>';
            
            // Send AJAX request to activate logo
            const formData = new FormData();
            formData.append('activate_logo', logoPath);
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Close modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById('logoSelectionModal'));
                    if (modal) {
                        modal.hide();
                    }
                    
                    // Show immediate selection notification
                    showNotification('✅ Logo selected: ' + logoName, 'success');
                    
                    // Reload page to show updated logo
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    // Restore original content
                    galleryElement.innerHTML = originalContent;
                    showNotification('❌ Failed to change logo: ' + (data.message || 'Unknown error'), 'error');
                }
            })
            .catch(error => {
                console.error('Logo selection error:', error);
                // Restore original content
                galleryElement.innerHTML = originalContent;
                showNotification('❌ Network error: ' + error.message, 'error');
            });
        }
        
        function uploadNewLogo() {
            // Handle logo upload
            const fileInput = document.getElementById('custom_logo');
            const file = fileInput.files[0];
            
            if (!file) {
                showNotification('❌ Please select a logo file first', 'error');
                return;
            }
            
            // Validate file type
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                showNotification('❌ Please select a valid image file (JPG, PNG, GIF, WebP)', 'error');
                return;
            }
            
            // Validate file size (5MB limit)
            if (file.size > 5 * 1024 * 1024) {
                showNotification('❌ File size must be less than 5MB', 'error');
                return;
            }
            
            // Create FormData and send AJAX request
            const formData = new FormData();
            formData.append('custom_logo', file);
            
            // Show loading state
            const uploadBtn = document.querySelector('#logoUploadForm button');
            const originalText = uploadBtn.innerHTML;
            uploadBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Uploading...';
            uploadBtn.disabled = true;
            
            // Show progress in gallery area
            const galleryElement = document.getElementById('logoGallery');
            const originalGalleryContent = galleryElement.innerHTML;
            galleryElement.innerHTML = '<div class="col-12 text-center py-5"><div class="spinner-border text-success" role="status"><span class="visually-hidden">Uploading...</span></div><p class="mt-2">Uploading logo...</p></div>';
            
            fetch(window.location.href, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    showNotification('✅ Logo uploaded: ' + (data.logo_path || 'New logo'), 'success');
                    // Reset form
                    document.getElementById('logoUploadForm').reset();
                    // Reload logo gallery
                    loadAvailableLogos();
                    // Reload page to show new logo
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                } else {
                    // Restore gallery content
                    galleryElement.innerHTML = originalGalleryContent;
                    showNotification('❌ Upload failed: ' + (data.message || 'Unknown error'), 'error');
                }
            })
            .catch(error => {
                console.error('Upload error:', error);
                // Restore gallery content
                galleryElement.innerHTML = originalGalleryContent;
                showNotification('❌ Upload error: ' + error.message, 'error');
            })
            .finally(() => {
                // Restore button state
                uploadBtn.innerHTML = originalText;
                uploadBtn.disabled = false;
            });
        }
        
        function toggleLogoDisplay(show) {
            // Send AJAX request to toggle logo display
            fetch(window.location.href, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'show_logo=' + (show ? 'yes' : 'no')
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(show ? '✅ Select logo: Display enabled' : '✅ Select logo: Display disabled', 'success');
                    // Reload page to reflect changes
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else {
                    showNotification('❌ Failed to update logo display', 'error');
                }
            })
            .catch(error => {
                console.error('Toggle error:', error);
                showNotification('❌ Network error occurred', 'error');
            });
        }
        
        function clearCustomLogo() {
            if (confirm('Are you sure you want to remove the custom logo?')) {
                // Send AJAX request to clear custom logo
                fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: 'clear_custom_logo=1'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification('✅ Select logo: Removed custom logo', 'success');
                        // Reload page to show changes
                        setTimeout(() => {
                            window.location.reload();
                        }, 1000);
                    } else {
                        showNotification('❌ Failed to remove custom logo', 'error');
                    }
                })
                .catch(error => {
                    console.error('Clear error:', error);
                    showNotification('❌ Network error occurred', 'error');
                });
            }
        }
        
        // Notification function
        function showNotification(message, type = 'info') {
            // Create notification element
            const notification = document.createElement('div');
            notification.className = `alert alert-${type} notification-container`;
            notification.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 9999;
                min-width: 300px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                border-radius: 8px;
                animation: slideInRight 0.3s ease-out;
            `;
            notification.innerHTML = message;
            
            // Add close button
            const closeBtn = document.createElement('button');
            closeBtn.type = 'button';
            closeBtn.className = 'btn-close';
            closeBtn.setAttribute('aria-label', 'Close');
            closeBtn.onclick = () => {
                notification.style.animation = 'slideOutRight 0.3s ease-in forwards';
                setTimeout(() => notification.remove(), 300);
            };
            notification.appendChild(closeBtn);
            
            // Add CSS animations
            if (!document.getElementById('notification-styles')) {
                const style = document.createElement('style');
                style.id = 'notification-styles';
                style.textContent = `
                    @keyframes slideInRight {
                        from { transform: translateX(100%); opacity: 0; }
                        to { transform: translateX(0); opacity: 1; }
                    }
                    @keyframes slideOutRight {
                        from { transform: translateX(0); opacity: 1; }
                        to { transform: translateX(100%); opacity: 0; }
                    }
                `;
                document.head.appendChild(style);
            }
            
            // Add to document
            document.body.appendChild(notification);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.style.animation = 'slideOutRight 0.3s ease-in forwards';
                    setTimeout(() => notification.remove(), 300);
                }
            }, 5000);
        }
        
        // Handle logo upload form submission
        document.getElementById('logoUploadForm')?.addEventListener('submit', function(e) {
            e.preventDefault();
            uploadNewLogo();
        });
    </script>
</body>
</html>