<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../includes/functions.php';

requireLogin();

// Check if user is admin
$currentUser = getCurrentUser();
if ($currentUser['role'] !== 'admin') {
    header('Location: dashboard.php');
    exit;
}

$success = '';
$error = '';

$slideshow_images = json_decode(getSiteSetting('slideshow_images') ?: '[]', true);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['update_logo'])) {
        // Handle logo upload
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] == UPLOAD_ERR_OK) {
            $uploadDir = '../assets/images/';
            $fileName = basename($_FILES['logo']['name']);
            $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
            $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'svg'];

            if (in_array(strtolower($fileExt), $allowedExts)) {
                $uniqueName = 'logo_' . time() . '.' . $fileExt;
                $uploadFile = $uploadDir . $uniqueName;

                if (move_uploaded_file($_FILES['logo']['tmp_name'], $uploadFile)) {
                    // Update logo setting
                    if (updateSiteSetting('site_logo', 'assets/images/' . $uniqueName)) {
                        $success = 'Logo uploaded successfully!';
                    } else {
                        $error = 'Error updating logo setting.';
                    }
                } else {
                    $error = 'Error uploading logo file.';
                }
            } else {
                $error = 'Invalid file type. Please upload JPG, PNG, GIF, or SVG files.';
            }
        } else {
            $error = 'Please select a logo file to upload.';
        }
    } elseif (isset($_POST['reset_logo'])) {
        // Reset to default icon
        if (updateSiteSetting('site_logo', 'fas fa-newspaper')) {
            $success = 'Logo reset to default!';
        } else {
            $error = 'Error resetting logo.';
        }
    } elseif (isset($_POST['update_site_name'])) {
        // Update site name
        $siteName = trim($_POST['site_name'] ?? '');
        if ($siteName) {
            if (updateSiteSetting('site_name', $siteName)) {
                $success = 'Site name updated successfully!';
            } else {
                $error = 'Error updating site name.';
            }
        } else {
            $error = 'Please enter a site name.';
        }
    } elseif (isset($_POST['add_slideshow_image'])) {
        // Add slideshow image
        $imageUrl = trim($_POST['image_url'] ?? '');
        $title = trim($_POST['slide_title'] ?? '');
        $description = trim($_POST['slide_description'] ?? '');
        $uploadSource = $_POST['upload_source'] ?? 'url';

        $finalImageUrl = '';

        if ($uploadSource === 'upload' && isset($_FILES['image_file']) && $_FILES['image_file']['error'] == UPLOAD_ERR_OK) {
            // Handle file upload
            $uploadDir = '../assets/images/slideshow/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            $fileName = basename($_FILES['image_file']['name']);
            $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
            $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];

            if (in_array(strtolower($fileExt), $allowedExts)) {
                $uniqueName = 'slide_' . time() . '_' . rand(1000, 9999) . '.' . $fileExt;
                $uploadFile = $uploadDir . $uniqueName;

                if (move_uploaded_file($_FILES['image_file']['tmp_name'], $uploadFile)) {
                    $finalImageUrl = 'assets/images/slideshow/' . $uniqueName;
                } else {
                    $error = 'Error uploading image file.';
                }
            } else {
                $error = 'Invalid file type. Please upload JPG, PNG, GIF, or WebP files.';
            }
        } elseif ($uploadSource === 'existing' && !empty($_POST['existing_image'])) {
            // Use existing image
            $existingImage = $_POST['existing_image'];
            if (file_exists('../' . $existingImage)) {
                $finalImageUrl = $existingImage;
            } else {
                $error = 'Selected image does not exist.';
            }
        } elseif ($uploadSource === 'url' && $imageUrl) {
            // Use URL
            $finalImageUrl = $imageUrl;
        } else {
            $error = 'Please provide an image source.';
        }

        if (!$error && $finalImageUrl) {
            $newImage = [
                'url' => $finalImageUrl,
                'title' => $title,
                'description' => $description,
                'source' => $uploadSource
            ];
            $slideshow_images[] = $newImage;

            if (updateSiteSetting('slideshow_images', json_encode($slideshow_images))) {
                $success = 'Slideshow image added successfully!';
            } else {
                $error = 'Error adding slideshow image.';
            }
        }
    } elseif (isset($_POST['delete_slideshow_image'])) {
        // Delete slideshow image
        $index = (int)($_POST['image_index'] ?? -1);
        if ($index >= 0 && isset($slideshow_images[$index])) {
            array_splice($slideshow_images, $index, 1);
            if (updateSiteSetting('slideshow_images', json_encode($slideshow_images))) {
                $success = 'Slideshow image deleted successfully!';
            } else {
                $error = 'Error deleting slideshow image.';
            }
        } else {
            $error = 'Invalid image index.';
        }
    } elseif (isset($_POST['update_slideshow_order'])) {
        // Update slideshow order
        $newOrder = json_decode($_POST['image_order'] ?? '[]', true);
        if (is_array($newOrder)) {
            $orderedImages = [];
            foreach ($newOrder as $index) {
                if (isset($slideshow_images[$index])) {
                    $orderedImages[] = $slideshow_images[$index];
                }
            }
            if (updateSiteSetting('slideshow_images', json_encode($orderedImages))) {
                $success = 'Slideshow order updated successfully!';
                $slideshow_images = $orderedImages;
            } else {
                $error = 'Error updating slideshow order.';
            }
        } else {
            $error = 'Invalid order data.';
        }
    } elseif (isset($_POST['update_welcome_text'])) {
        // Update welcome text
        $welcome_title = trim($_POST['welcome_title'] ?? '');
        $welcome_description = trim($_POST['welcome_description'] ?? '');
        
        if ($welcome_title) {
            if (updateSiteSetting('welcome_title', $welcome_title)) {
                $success = 'Welcome title updated successfully!';
            } else {
                $error = 'Error updating welcome title.';
            }
        } else {
            $error = 'Please enter a welcome title.';
        }
        
        if (!$error && $welcome_description !== '') {
            if (!updateSiteSetting('welcome_description', $welcome_description)) {
                $error = 'Error updating welcome description.';
            }
        }
    } elseif (isset($_POST['update_paynow_settings'])) {
        // Update Paynow settings
        $paynow_integration_id = trim($_POST['paynow_integration_id'] ?? '');
        $paynow_integration_key = trim($_POST['paynow_integration_key'] ?? '');
        $paynow_result_url = trim($_POST['paynow_result_url'] ?? '');
        $paynow_return_url = trim($_POST['paynow_return_url'] ?? '');

        $settingsUpdated = true;

        if (!updateSiteSetting('paynow_integration_id', $paynow_integration_id)) {
            $settingsUpdated = false;
        }
        if (!updateSiteSetting('paynow_integration_key', $paynow_integration_key)) {
            $settingsUpdated = false;
        }
        if (!updateSiteSetting('paynow_result_url', $paynow_result_url)) {
            $settingsUpdated = false;
        }
        if (!updateSiteSetting('paynow_return_url', $paynow_return_url)) {
            $settingsUpdated = false;
        }

        if ($settingsUpdated) {
            $success = 'Paynow settings updated successfully!';
        } else {
            $error = 'Error updating Paynow settings.';
        }
    } elseif (isset($_POST['update_home_sections'])) {
        // Update Home Page Section Settings
        $available_exams_title = trim($_POST['available_exams_title'] ?? '');
        $available_exams_subtitle = trim($_POST['available_exams_subtitle'] ?? '');
        $knowledge_insight_title = trim($_POST['knowledge_insight_title'] ?? '');
        $knowledge_insight_subtitle = trim($_POST['knowledge_insight_subtitle'] ?? '');

        $settingsUpdated = true;

        if (!updateSiteSetting('available_exams_title', $available_exams_title)) {
            $settingsUpdated = false;
        }
        if (!updateSiteSetting('available_exams_subtitle', $available_exams_subtitle)) {
            $settingsUpdated = false;
        }
        if (!updateSiteSetting('knowledge_insight_title', $knowledge_insight_title)) {
            $settingsUpdated = false;
        }
        if (!updateSiteSetting('knowledge_insight_subtitle', $knowledge_insight_subtitle)) {
            $settingsUpdated = false;
        }

        if ($settingsUpdated) {
            $success = 'Home page sections updated successfully!';
        } else {
            $error = 'Error updating home page sections.';
        }
    }
}

// Get current settings
$currentLogo = getSiteSetting('site_logo') ?: 'fas fa-newspaper';
$currentSiteName = getSiteSetting('site_name') ?: 'Instructor Panel';
$currentWelcomeTitle = getSiteSetting('welcome_title') ?: 'Welcome to Mutalex Academy';
$currentWelcomeDescription = getSiteSetting('welcome_description') ?: 'Your premier destination for the latest news, insightful articles,journals and academic content for various professional courses . Stay informed and inspired with our diverse content.';
$currentPaynowIntegrationId = getSiteSetting('paynow_integration_id') ?: '';
$currentPaynowIntegrationKey = getSiteSetting('paynow_integration_key') ?: '';
$currentPaynowResultUrl = getSiteSetting('paynow_result_url') ?: '';
$currentPaynowReturnUrl = getSiteSetting('paynow_return_url') ?: '';

// Home Page Section Settings
$availableExamsTitle = getSiteSetting('available_exams_title') ?: 'Available Exams';
$availableExamsSubtitle = getSiteSetting('available_exams_subtitle') ?: 'Test your knowledge with our comprehensive exam collection';
$knowledgeInsightTitle = getSiteSetting('knowledge_insight_title') ?: 'Knowledge & Insight';
$knowledgeInsightSubtitle = getSiteSetting('knowledge_insight_subtitle') ?: 'Stay informed with our latest news and articles';

$page_title = 'Site Settings';
include 'includes/admin_header.php';
?>

<?php if ($error): ?>
    <div class="mb-6 bg-red-50 border-l-4 border-red-500 p-4 rounded-r-lg shadow-sm animate-pulse">
        <div class="flex items-center">
            <div class="flex-shrink-0">
                <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
            </div>
            <div class="ml-3">
                <p class="text-red-700 font-medium"><?php echo htmlspecialchars($error); ?></p>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="mb-6 bg-green-50 border-l-4 border-green-500 p-4 rounded-r-lg shadow-sm">
        <div class="flex items-center">
            <div class="flex-shrink-0">
                <i class="fas fa-check-circle text-green-500 text-xl"></i>
            </div>
            <div class="ml-3">
                <p class="text-green-700 font-medium"><?php echo htmlspecialchars($success); ?></p>
            </div>
        </div>
    </div>
<?php endif; ?>

<!-- Settings Navigation Tabs -->
<div class="mb-8">
    <div class="border-b border-gray-200">
        <nav class="-mb-px flex space-x-8 overflow-x-auto" aria-label="Settings tabs">
            <button onclick="switchTab('general')" id="tab-general" class="tab-btn border-primary-blue text-primary-blue whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm flex items-center gap-2">
                <i class="fas fa-cog"></i> General Settings
            </button>
            <button onclick="switchTab('slideshow')" id="tab-slideshow" class="tab-btn border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm flex items-center gap-2">
                <i class="fas fa-images"></i> Slideshow
            </button>
            <button onclick="switchTab('payment')" id="tab-payment" class="tab-btn border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm flex items-center gap-2">
                <i class="fas fa-credit-card"></i> Payment Gateway
            </button>
            <button onclick="switchTab('home_sections')" id="tab-home_sections" class="tab-btn border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm flex items-center gap-2">
                <i class="fas fa-home"></i> Home Sections
            </button>
        </nav>
    </div>
</div>

<!-- General Settings Tab -->
<div id="content-general" class="tab-content">
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- Logo Settings Card -->
        <div class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden hover:shadow-xl transition-shadow duration-300">
            <div class="bg-gradient-to-r from-primary-blue to-blue-600 px-6 py-4">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-white/20 rounded-lg">
                        <i class="fas fa-image text-white text-xl"></i>
                    </div>
                    <div>
                        <h3 class="text-lg font-semibold text-white">Logo Settings</h3>
                        <p class="text-blue-100 text-sm">Upload and manage your site logo</p>
                    </div>
                </div>
            </div>
            <div class="p-6">
                <div class="mb-6">
                    <label class="block text-sm font-semibold text-gray-700 mb-3">Current Logo Preview</label>
                    <div class="bg-gray-50 rounded-xl p-6 border-2 border-dashed border-gray-200 flex items-center justify-center min-h-[120px]">
                        <div class="text-center">
                            <?php if (strpos($currentLogo, 'assets/images/') === 0): ?>
                                <img src="../<?php echo htmlspecialchars($currentLogo); ?>" alt="Site Logo" class="max-h-16 mx-auto mb-2">
                                <p class="text-xs text-gray-500">Custom Image Logo</p>
                            <?php else: ?>
                                <i class="<?php echo htmlspecialchars($currentLogo); ?>" style="font-size: 3rem; color: #1E3A8A;"></i>
                                <p class="text-xs text-gray-500 mt-2">Default Icon</p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <form method="POST" enctype="multipart/form-data">
                    <div class="mb-4">
                        <label for="logo" class="block text-sm font-medium text-gray-700 mb-2">Upload New Logo</label>
                        <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg hover:bg-gray-50 transition-colors cursor-pointer" id="upload-area">
                            <div class="space-y-1 text-center">
                                <i class="fas fa-cloud-upload-alt text-gray-400 text-3xl mb-3"></i>
                                <div class="flex text-sm text-gray-600">
                                    <label for="logo" class="relative cursor-pointer bg-white rounded-md font-medium text-primary-blue hover:text-blue-700 focus-within:outline-none">
                                        <span>Upload a file</span>
                                        <input type="file" id="logo" name="logo" accept="image/*" class="sr-only" onchange="updateFileName(this)">
                                    </label>
                                    <p class="pl-1">or drag and drop</p>
                                </div>
                                <p class="text-xs text-gray-500" id="file-name">PNG, JPG, GIF, SVG up to 2MB</p>
                            </div>
                        </div>
                    </div>
                    <div class="flex gap-3">
                        <button type="submit" name="update_logo" class="flex-1 bg-gradient-to-r from-primary-blue to-blue-600 text-white py-2.5 px-4 rounded-lg font-medium hover:from-blue-700 hover:to-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 transition-all shadow-md">
                            <i class="fas fa-upload mr-2"></i>Upload Logo
                        </button>
                        <button type="submit" name="reset_logo" class="px-4 py-2.5 bg-gray-100 text-gray-700 rounded-lg font-medium hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 transition-all">
                            <i class="fas fa-undo mr-2"></i>Reset
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Site Name Settings Card -->
        <div class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden hover:shadow-xl transition-shadow duration-300">
            <div class="bg-gradient-to-r from-emerald-500 to-emerald-600 px-6 py-4">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-white/20 rounded-lg">
                        <i class="fas fa-heading text-white text-xl"></i>
                    </div>
                    <div>
                        <h3 class="text-lg font-semibold text-white">Site Name</h3>
                        <p class="text-emerald-100 text-sm">Configure your website name</p>
                    </div>
                </div>
            </div>
            <div class="p-6">
                <form method="POST">
                    <div class="mb-4">
                        <label for="site_name" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-tag mr-2 text-gray-400"></i>Site Name
                        </label>
                        <input type="text" id="site_name" name="site_name" value="<?php echo htmlspecialchars($currentSiteName); ?>" required 
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-all placeholder-gray-400"
                            placeholder="Enter your site name">
                    </div>
                    <button type="submit" name="update_site_name" class="w-full bg-gradient-to-r from-emerald-500 to-emerald-600 text-white py-3 px-4 rounded-lg font-medium hover:from-emerald-600 hover:to-emerald-600 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2 transition-all shadow-md">
                        <i class="fas fa-save mr-2"></i>Update Site Name
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- Welcome Text Settings Card -->
    <div class="mt-6 bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden hover:shadow-xl transition-shadow duration-300">
        <div class="bg-gradient-to-r from-violet-500 to-violet-600 px-6 py-4">
            <div class="flex items-center gap-3">
                <div class="p-2 bg-white/20 rounded-lg">
                    <i class="fas fa-welcome text-white text-xl"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Welcome Section</h3>
                    <p class="text-violet-100 text-sm">Edit the hero section welcome message</p>
                </div>
            </div>
        </div>
        <div class="p-6">
            <form method="POST">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="welcome_title" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-heading mr-2 text-gray-400"></i>Welcome Title
                        </label>
                        <input type="text" id="welcome_title" name="welcome_title" value="<?php echo htmlspecialchars($currentWelcomeTitle); ?>" required 
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500 focus:border-violet-500 transition-all placeholder-gray-400"
                            placeholder="Enter welcome title">
                        <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                            <i class="fas fa-info-circle"></i> The main heading displayed in the hero section
                        </p>
                    </div>
                    <div>
                        <label for="welcome_description" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-align-left mr-2 text-gray-400"></i>Welcome Description
                        </label>
                        <textarea id="welcome_description" name="welcome_description" rows="3" required 
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-violet-500 focus:border-violet-500 transition-all placeholder-gray-400 resize-none"
                            placeholder="Enter welcome description"><?php echo htmlspecialchars($currentWelcomeDescription); ?></textarea>
                        <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                            <i class="fas fa-info-circle"></i> The description text displayed below the title
                        </p>
                    </div>
                </div>
                <div class="mt-6">
                    <button type="submit" name="update_welcome_text" class="bg-gradient-to-r from-violet-500 to-violet-600 text-white py-3 px-6 rounded-lg font-medium hover:from-violet-600 hover:to-violet-600 focus:outline-none focus:ring-2 focus:ring-violet-500 focus:ring-offset-2 transition-all shadow-md">
                        <i class="fas fa-save mr-2"></i>Update Welcome Text
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Slideshow Settings Tab -->
<div id="content-slideshow" class="tab-content hidden">
    <div class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
        <div class="bg-gradient-to-r from-amber-500 to-orange-500 px-6 py-4">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="p-2 bg-white/20 rounded-lg">
                        <i class="fas fa-images text-white text-xl"></i>
                    </div>
                    <div>
                        <h3 class="text-lg font-semibold text-white">Slideshow Management</h3>
                        <p class="text-amber-100 text-sm">Manage homepage slideshow images</p>
                    </div>
                </div>
                <span class="bg-white/20 text-white px-3 py-1 rounded-full text-sm font-medium">
                    <?php echo count($slideshow_images); ?> Images
                </span>
            </div>
        </div>
        
        <div class="p-6">
            <!-- Current Slideshow Images -->
            <?php if (!empty($slideshow_images)): ?>
                <div class="mb-8">
                    <h4 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                        <i class="fas fa-list-alt text-amber-500"></i> Current Slideshow Images
                    </h4>
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4" id="slideshow-images-list">
                        <?php foreach ($slideshow_images as $index => $image): ?>
                            <div class="bg-gray-50 rounded-xl p-4 border border-gray-200 hover:border-amber-300 hover:shadow-md transition-all group">
                                <div class="relative mb-3">
                                    <img src="<?php echo htmlspecialchars($image['url']); ?>" alt="Slide <?php echo $index + 1; ?>" class="w-full h-32 object-cover rounded-lg">
                                    <div class="absolute top-2 right-2 bg-black/50 text-white px-2 py-1 rounded text-xs">
                                        #<?php echo $index + 1; ?>
                                    </div>
                                </div>
                                <h5 class="font-semibold text-gray-800 mb-1"><?php echo htmlspecialchars($image['title'] ?: 'No title'); ?></h5>
                                <p class="text-sm text-gray-500 mb-3 line-clamp-2"><?php echo htmlspecialchars($image['description'] ?: 'No description'); ?></p>
                                <form method="POST" class="inline-block">
                                    <input type="hidden" name="image_index" value="<?php echo $index; ?>">
                                    <button type="submit" name="delete_slideshow_image" class="w-full bg-red-50 text-red-600 py-2 px-3 rounded-lg text-sm font-medium hover:bg-red-100 transition-colors flex items-center justify-center gap-2" onclick="return confirm('Are you sure you want to delete this image?')">
                                        <i class="fas fa-trash-alt"></i> Delete
                                    </button>
                                </form>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php else: ?>
                <div class="mb-8 text-center py-8 bg-gray-50 rounded-xl border-2 border-dashed border-gray-200">
                    <i class="fas fa-image text-gray-300 text-5xl mb-4"></i>
                    <p class="text-gray-500 font-medium">No slideshow images yet</p>
                    <p class="text-gray-400 text-sm">Add your first image below</p>
                </div>
            <?php endif; ?>

            <!-- Add New Image Form -->
            <div class="border-t border-gray-200 pt-6">
                <h4 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                    <i class="fas fa-plus-circle text-amber-500"></i> Add New Slideshow Image
                </h4>
                <form method="POST" enctype="multipart/form-data" class="bg-gray-50 rounded-xl p-6 border border-gray-200">
                    <!-- Upload Source Selection -->
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-3">Image Source</label>
                        <div class="grid grid-cols-3 gap-3">
                            <label class="cursor-pointer">
                                <input type="radio" name="upload_source" value="upload" class="peer sr-only" onchange="toggleUploadFields()" checked>
                                <div class="px-4 py-3 rounded-lg border-2 border-gray-200 peer-checked:border-amber-500 peer-checked:bg-amber-50 hover:bg-gray-100 transition-all text-center">
                                    <i class="fas fa-upload text-gray-600 mb-1 block"></i>
                                    <span class="text-sm font-medium text-gray-700">Upload</span>
                                </div>
                            </label>
                            <label class="cursor-pointer">
                                <input type="radio" name="upload_source" value="existing" class="peer sr-only" onchange="toggleUploadFields()">
                                <div class="px-4 py-3 rounded-lg border-2 border-gray-200 peer-checked:border-amber-500 peer-checked:bg-amber-50 hover:bg-gray-100 transition-all text-center">
                                    <i class="fas fa-folder text-gray-600 mb-1 block"></i>
                                    <span class="text-sm font-medium text-gray-700">Existing</span>
                                </div>
                            </label>
                            <label class="cursor-pointer">
                                <input type="radio" name="upload_source" value="url" class="peer sr-only" onchange="toggleUploadFields()">
                                <div class="px-4 py-3 rounded-lg border-2 border-gray-200 peer-checked:border-amber-500 peer-checked:bg-amber-50 hover:bg-gray-100 transition-all text-center">
                                    <i class="fas fa-link text-gray-600 mb-1 block"></i>
                                    <span class="text-sm font-medium text-gray-700">URL</span>
                                </div>
                            </label>
                        </div>
                    </div>

                    <!-- File Upload Field -->
                    <div class="form-group upload-field mb-4" id="upload_field">
                        <label for="image_file" class="block text-sm font-medium text-gray-700 mb-2">Select Image File</label>
                        <input type="file" id="image_file" name="image_file" accept="image/*" 
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition-all">
                        <p class="mt-1 text-xs text-gray-500">Supported: JPG, PNG, GIF, WebP. Max size: 5MB.</p>
                    </div>

                    <!-- Existing Images Field -->
                    <div class="form-group existing-field mb-4 hidden" id="existing_field">
                        <label for="existing_image" class="block text-sm font-medium text-gray-700 mb-2">Select Existing Image</label>
                        <select id="existing_image" name="existing_image" 
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition-all">
                            <option value="">Choose an image...</option>
                            <?php
                            $existingImages = glob('../assets/images/*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE);
                            foreach ($existingImages as $image) {
                                $imagePath = 'assets/images/' . basename($image);
                                echo '<option value="' . htmlspecialchars($imagePath) . '">' . htmlspecialchars(basename($image)) . '</option>';
                            }
                            ?>
                        </select>
                    </div>

                    <!-- URL Field -->
                    <div class="form-group url-field mb-4 hidden" id="url_field">
                        <label for="image_url" class="block text-sm font-medium text-gray-700 mb-2">Image URL</label>
                        <input type="url" id="image_url" name="image_url" placeholder="https://example.com/image.jpg" 
                            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition-all">
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label for="slide_title" class="block text-sm font-medium text-gray-700 mb-2">Title (optional)</label>
                            <input type="text" id="slide_title" name="slide_title" placeholder="Enter slide title" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition-all">
                        </div>
                        <div>
                            <label for="slide_description" class="block text-sm font-medium text-gray-700 mb-2">Description (optional)</label>
                            <textarea id="slide_description" name="slide_description" rows="2" placeholder="Enter slide description" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-amber-500 transition-all resize-none"></textarea>
                        </div>
                    </div>
                    
                    <button type="submit" name="add_slideshow_image" class="w-full bg-gradient-to-r from-amber-500 to-orange-500 text-white py-3 px-4 rounded-lg font-medium hover:from-amber-600 hover:to-orange-600 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 transition-all shadow-md">
                        <i class="fas fa-plus mr-2"></i>Add Slideshow Image
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Payment Gateway Tab -->
<div id="content-payment" class="tab-content hidden">
    <div class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
        <div class="bg-gradient-to-r from-cyan-500 to-blue-600 px-6 py-4">
            <div class="flex items-center gap-3">
                <div class="p-2 bg-white/20 rounded-lg">
                    <i class="fas fa-credit-card text-white text-xl"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Paynow Payment Gateway</h3>
                    <p class="text-cyan-100 text-sm">Configure Paynow integration settings</p>
                </div>
            </div>
        </div>
        <div class="p-6">
            <form method="POST">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="paynow_integration_id" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-id-card mr-2 text-gray-400"></i>Integration ID
                        </label>
                        <div class="relative">
                            <input type="text" id="paynow_integration_id" name="paynow_integration_id" value="<?php echo htmlspecialchars($currentPaynowIntegrationId); ?>" 
                                placeholder="Enter your Paynow Integration ID"
                                class="w-full px-4 py-3 pl-11 border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:border-cyan-500 transition-all">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fas fa-user text-gray-400"></i>
                            </div>
                        </div>
                        <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                            <i class="fas fa-info-circle"></i> The Integration ID provided by Paynow
                        </p>
                    </div>
                    <div>
                        <label for="paynow_integration_key" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-key mr-2 text-gray-400"></i>Integration Key
                        </label>
                        <div class="relative">
                            <input type="password" id="paynow_integration_key" name="paynow_integration_key" value="<?php echo htmlspecialchars($currentPaynowIntegrationKey); ?>" 
                                placeholder="Enter your Paynow Integration Key"
                                class="w-full px-4 py-3 pl-11 border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:border-cyan-500 transition-all">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fas fa-lock text-gray-400"></i>
                            </div>
                        </div>
                        <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                            <i class="fas fa-info-circle"></i> Keep this key secret and secure
                        </p>
                    </div>
                    <div>
                        <label for="paynow_result_url" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-server mr-2 text-gray-400"></i>Result URL
                        </label>
                        <div class="relative">
                            <input type="url" id="paynow_result_url" name="paynow_result_url" value="<?php echo htmlspecialchars($currentPaynowResultUrl); ?>" 
                                placeholder="https://yourdomain.com/gateways/paynow/update"
                                class="w-full px-4 py-3 pl-11 border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:border-cyan-500 transition-all">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fas fa-link text-gray-400"></i>
                            </div>
                        </div>
                        <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                            <i class="fas fa-info-circle"></i> URL for payment status updates
                        </p>
                    </div>
                    <div>
                        <label for="paynow_return_url" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-sign-in-alt mr-2 text-gray-400"></i>Return URL
                        </label>
                        <div class="relative">
                            <input type="url" id="paynow_return_url" name="paynow_return_url" value="<?php echo htmlspecialchars($currentPaynowReturnUrl); ?>" 
                                placeholder="https://yourdomain.com/return?gateway=paynow"
                                class="w-full px-4 py-3 pl-11 border border-gray-300 rounded-lg focus:ring-2 focus:ring-cyan-500 focus:border-cyan-500 transition-all">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fas fa-redo text-gray-400"></i>
                            </div>
                        </div>
                        <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                            <i class="fas fa-info-circle"></i> User redirect after payment
                        </p>
                    </div>
                </div>
                <div class="mt-6">
                    <button type="submit" name="update_paynow_settings" class="bg-gradient-to-r from-cyan-500 to-blue-600 text-white py-3 px-6 rounded-lg font-medium hover:from-cyan-600 hover:to-blue-700 focus:outline-none focus:ring-2 focus:ring-cyan-500 focus:ring-offset-2 transition-all shadow-md">
                        <i class="fas fa-save mr-2"></i>Update Paynow Settings
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Home Page Sections Tab -->
<div id="content-home_sections" class="tab-content hidden">
    <div class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
        <div class="bg-gradient-to-r from-indigo-500 to-purple-600 px-6 py-4">
            <div class="flex items-center gap-3">
                <div class="p-2 bg-white/20 rounded-lg">
                    <i class="fas fa-home text-white text-xl"></i>
                </div>
                <div>
                    <h3 class="text-lg font-semibold text-white">Home Page Sections</h3>
                    <p class="text-indigo-100 text-sm">Edit the Available Exams and Knowledge & Insight sections</p>
                </div>
            </div>
        </div>
        <div class="p-6">
            <form method="POST">
                <!-- Available Exams Section -->
                <div class="mb-8">
                    <h4 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                        <i class="fas fa-clipboard-check text-indigo-500"></i> Available Exams Section
                    </h4>
                    <div class="bg-indigo-50 rounded-xl p-6 border border-indigo-100">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label for="available_exams_title" class="block text-sm font-medium text-gray-700 mb-2">
                                    <i class="fas fa-heading mr-2 text-gray-400"></i>Section Title
                                </label>
                                <input type="text" id="available_exams_title" name="available_exams_title" value="<?php echo htmlspecialchars($availableExamsTitle); ?>" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all placeholder-gray-400"
                                    placeholder="Available Exams">
                                <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                                    <i class="fas fa-info-circle"></i> The main heading for the exams section
                                </p>
                            </div>
                            <div>
                                <label for="available_exams_subtitle" class="block text-sm font-medium text-gray-700 mb-2">
                                    <i class="fas fa-align-left mr-2 text-gray-400"></i>Section Subtitle
                                </label>
                                <textarea id="available_exams_subtitle" name="available_exams_subtitle" rows="3" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-all placeholder-gray-400 resize-none"
                                    placeholder="Test your knowledge with our comprehensive exam collection"><?php echo htmlspecialchars($availableExamsSubtitle); ?></textarea>
                                <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                                    <i class="fas fa-info-circle"></i> The description text displayed below the title
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Knowledge & Insight Section -->
                <div class="mb-6">
                    <h4 class="text-lg font-semibold text-gray-800 mb-4 flex items-center gap-2">
                        <i class="fas fa-book-open text-purple-500"></i> Knowledge & Insight Section
                    </h4>
                    <div class="bg-purple-50 rounded-xl p-6 border border-purple-100">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label for="knowledge_insight_title" class="block text-sm font-medium text-gray-700 mb-2">
                                    <i class="fas fa-heading mr-2 text-gray-400"></i>Section Title
                                </label>
                                <input type="text" id="knowledge_insight_title" name="knowledge_insight_title" value="<?php echo htmlspecialchars($knowledgeInsightTitle); ?>" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition-all placeholder-gray-400"
                                    placeholder="Knowledge & Insight">
                                <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                                    <i class="fas fa-info-circle"></i> The main heading for the articles section
                                </p>
                            </div>
                            <div>
                                <label for="knowledge_insight_subtitle" class="block text-sm font-medium text-gray-700 mb-2">
                                    <i class="fas fa-align-left mr-2 text-gray-400"></i>Section Subtitle
                                </label>
                                <textarea id="knowledge_insight_subtitle" name="knowledge_insight_subtitle" rows="3" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition-all placeholder-gray-400 resize-none"
                                    placeholder="Stay informed with our latest news and articles"><?php echo htmlspecialchars($knowledgeInsightSubtitle); ?></textarea>
                                <p class="mt-2 text-xs text-gray-500 flex items-center gap-1">
                                    <i class="fas fa-info-circle"></i> The description text displayed below the title
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mt-6">
                    <button type="submit" name="update_home_sections" class="bg-gradient-to-r from-indigo-500 to-purple-600 text-white py-3 px-6 rounded-lg font-medium hover:from-indigo-600 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 transition-all shadow-md">
                        <i class="fas fa-save mr-2"></i>Update Home Page Sections
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
    .tab-btn {
        transition: all 0.2s ease;
    }
    .tab-btn:hover {
        background-color: rgba(30, 58, 138, 0.05);
    }
    .tab-btn.active {
        border-color: #1E3A8A;
        color: #1E3A8A;
    }
    .line-clamp-2 {
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
    }
    .tab-content {
        animation: fadeIn 0.3s ease-in-out;
    }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
</style>

<script>
    function switchTab(tabName) {
        // Hide all tab contents
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.add('hidden');
        });
        
        // Remove active class from all tabs
        document.querySelectorAll('.tab-btn').forEach(btn => {
            btn.classList.remove('border-primary-blue', 'text-primary-blue');
            btn.classList.add('border-transparent', 'text-gray-500');
        });
        
        // Show selected tab content
        document.getElementById('content-' + tabName).classList.remove('hidden');
        
        // Add active class to selected tab
        const activeTab = document.getElementById('tab-' + tabName);
        activeTab.classList.remove('border-transparent', 'text-gray-500');
        activeTab.classList.add('border-primary-blue', 'text-primary-blue');
    }

    function toggleUploadFields() {
        const source = document.querySelector('input[name="upload_source"]:checked').value;
        const uploadField = document.getElementById('upload_field');
        const existingField = document.getElementById('existing_field');
        const urlField = document.getElementById('url_field');

        // Hide all fields first
        uploadField.classList.add('hidden');
        existingField.classList.add('hidden');
        urlField.classList.add('hidden');

        // Show selected field
        switch(source) {
            case 'upload':
                uploadField.classList.remove('hidden');
                break;
            case 'existing':
                existingField.classList.remove('hidden');
                break;
            case 'url':
                urlField.classList.remove('hidden');
                break;
        }
    }

    function updateFileName(input) {
        const fileNameDisplay = document.getElementById('file-name');
        if (input.files && input.files[0]) {
            fileNameDisplay.textContent = input.files[0].name + ' selected';
        } else {
            fileNameDisplay.textContent = 'PNG, JPG, GIF, SVG up to 2MB';
        }
    }

    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        toggleUploadFields();
    });
</script>

<?php include 'includes/admin_footer.php'; ?>
