<?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_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.';
        }
    }
}

// Get current settings
$currentLogo = getSiteSetting('site_logo') ?: 'fas fa-newspaper';
$currentSiteName = getSiteSetting('site_name') ?: 'Instructor Panel';
$currentPaynowIntegrationId = getSiteSetting('paynow_integration_id') ?: '';
$currentPaynowIntegrationKey = getSiteSetting('paynow_integration_key') ?: '';
$currentPaynowResultUrl = getSiteSetting('paynow_result_url') ?: '';
$currentPaynowReturnUrl = getSiteSetting('paynow_return_url') ?: '';

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

<?php if ($error): ?>
    <div class="alert alert-error">
        <?php echo htmlspecialchars($error); ?>
    </div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert alert-success">
        <?php echo htmlspecialchars($success); ?>
    </div>
<?php endif; ?>

<div class="settings-section">
    <h2>Site Settings</h2>

    <!-- Logo Settings -->
    <div class="settings-card">
        <h3>Logo Settings</h3>
        <div class="current-logo-preview">
            <h4>Current Logo:</h4>
            <div class="logo-preview">
                <?php if (strpos($currentLogo, 'assets/images/') === 0): ?>
                    <img src="../<?php echo htmlspecialchars($currentLogo); ?>" alt="Site Logo" style="max-height: 60px;">
                <?php else: ?>
                    <i class="<?php echo htmlspecialchars($currentLogo); ?>" style="font-size: 3rem; color: #2563eb;"></i>
                <?php endif; ?>
            </div>
        </div>

        <form method="POST" enctype="multipart/form-data" style="margin-top: 2rem;">
            <div class="form-group">
                <label for="logo">Upload New Logo:</label>
                <input type="file" id="logo" name="logo" accept="image/*">
                <small>Supported formats: JPG, PNG, GIF, SVG. Recommended size: 200x60px or smaller.</small>
            </div>
            <div class="form-actions">
                <button type="submit" name="update_logo" class="btn btn-primary">Upload Logo</button>
                <button type="submit" name="reset_logo" class="btn btn-secondary">Reset to Default</button>
            </div>
        </form>
    </div>

    <!-- Site Name Settings -->
    <div class="settings-card">
        <h3>Site Name Settings</h3>
        <form method="POST">
            <div class="form-group">
                <label for="site_name">Site Name:</label>
                <input type="text" id="site_name" name="site_name" value="<?php echo htmlspecialchars($currentSiteName); ?>" required>
            </div>
            <div class="form-actions">
                <button type="submit" name="update_site_name" class="btn btn-primary">Update Site Name</button>
            </div>
        </form>
    </div>

    <!-- Slideshow Settings -->
    <div class="settings-card">
        <h3>Slideshow Settings</h3>
        <p class="settings-description">Manage the homepage slideshow images. You can add images with titles and descriptions.</p>

        <!-- Current Slideshow Images -->
        <?php if (!empty($slideshow_images)): ?>
            <div class="current-slideshow">
                <h4>Current Slideshow Images:</h4>
                <div class="slideshow-images-list" id="slideshow-images-list">
                    <?php foreach ($slideshow_images as $index => $image): ?>
                        <div class="slideshow-image-item" data-index="<?php echo $index; ?>">
                            <div class="image-preview">
                                <img src="<?php echo htmlspecialchars($image['url']); ?>" alt="Slide <?php echo $index + 1; ?>" style="max-width: 100px; max-height: 60px; object-fit: cover;">
                            </div>
                            <div class="image-details">
                                <strong><?php echo htmlspecialchars($image['title'] ?: 'No title'); ?></strong>
                                <p><?php echo htmlspecialchars($image['description'] ?: 'No description'); ?></p>
                            </div>
                            <div class="image-actions">
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="image_index" value="<?php echo $index; ?>">
                                    <button type="submit" name="delete_slideshow_image" class="btn btn-outline btn-sm" onclick="return confirm('Are you sure you want to delete this image?')">Delete</button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endif; ?>

        <!-- Add New Image Form -->
        <div class="add-slideshow-form">
            <h4>Add New Slideshow Image:</h4>
            <form method="POST" enctype="multipart/form-data">
                <!-- Upload Source Selection -->
                <div class="form-group">
                    <label for="upload_source">Image Source:</label>
                    <select id="upload_source" name="upload_source" onchange="toggleUploadFields()">
                        <option value="upload">Upload New Image</option>
                        <option value="existing">Use Existing Image</option>
                        <option value="url">Image URL</option>
                    </select>
                </div>

                <!-- File Upload Field -->
                <div class="form-group upload-field" id="upload_field">
                    <label for="image_file">Select Image File:</label>
                    <input type="file" id="image_file" name="image_file" accept="image/*">
                    <small>Supported formats: JPG, PNG, GIF, WebP. Max size: 5MB.</small>
                </div>

                <!-- Existing Images Field -->
                <div class="form-group existing-field" id="existing_field" style="display: none;">
                    <label for="existing_image">Select Existing Image:</label>
                    <select id="existing_image" name="existing_image">
                        <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>
                    <small>Select from images already uploaded to the site.</small>
                </div>

                <!-- URL Field -->
                <div class="form-group url-field" id="url_field" style="display: none;">
                    <label for="image_url">Image URL:</label>
                    <input type="url" id="image_url" name="image_url" placeholder="https://example.com/image.jpg">
                    <small>Enter the full URL of the image you want to use in the slideshow.</small>
                </div>

                <div class="form-group">
                    <label for="slide_title">Title (optional):</label>
                    <input type="text" id="slide_title" name="slide_title" placeholder="Enter slide title">
                </div>
                <div class="form-group">
                    <label for="slide_description">Description (optional):</label>
                    <textarea id="slide_description" name="slide_description" rows="3" placeholder="Enter slide description"></textarea>
                </div>
                <div class="form-actions">
                    <button type="submit" name="add_slideshow_image" class="btn btn-primary">Add Image</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Payment Gateway Settings -->
    <div class="settings-card">
        <h3>Payment Gateway Settings</h3>
        <p class="settings-description">Configure Paynow payment gateway integration settings.</p>
        <form method="POST">
            <div class="form-group">
                <label for="paynow_integration_id">Integration ID:</label>
                <input type="text" id="paynow_integration_id" name="paynow_integration_id" value="<?php echo htmlspecialchars($currentPaynowIntegrationId); ?>" placeholder="Enter your Paynow Integration ID">
                <small>The Integration ID provided by Paynow for your account.</small>
            </div>
            <div class="form-group">
                <label for="paynow_integration_key">Integration Key:</label>
                <input type="password" id="paynow_integration_key" name="paynow_integration_key" value="<?php echo htmlspecialchars($currentPaynowIntegrationKey); ?>" placeholder="Enter your Paynow Integration Key">
                <small>The Integration Key provided by Paynow for your account.</small>
            </div>
            <div class="form-group">
                <label for="paynow_result_url">Result URL:</label>
                <input type="url" id="paynow_result_url" name="paynow_result_url" value="<?php echo htmlspecialchars($currentPaynowResultUrl); ?>" placeholder="https://yourdomain.com/gateways/paynow/update">
                <small>The URL where Paynow will send payment status updates.</small>
            </div>
            <div class="form-group">
                <label for="paynow_return_url">Return URL:</label>
                <input type="url" id="paynow_return_url" name="paynow_return_url" value="<?php echo htmlspecialchars($currentPaynowReturnUrl); ?>" placeholder="https://yourdomain.com/return?gateway=paynow">
                <small>The URL where users will be redirected after payment completion.</small>
            </div>
            <div class="form-actions">
                <button type="submit" name="update_paynow_settings" class="btn btn-primary">Update Paynow Settings</button>
            </div>
        </form>
    </div>
</div>

<style>
.settings-section {
    max-width: 800px;
}

.settings-section h2 {
    font-size: 1.875rem;
    font-weight: 700;
    color: #1f2937;
    margin-bottom: 2rem;
}

.settings-card {
    background: white;
    padding: 2rem;
    border-radius: 0.75rem;
    box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 2rem;
}

.settings-card h3 {
    font-size: 1.25rem;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 1.5rem;
}

.current-logo-preview {
    margin-bottom: 1.5rem;
}

.current-logo-preview h4 {
    font-size: 1rem;
    font-weight: 600;
    color: #374151;
    margin-bottom: 0.5rem;
}

.logo-preview {
    padding: 1rem;
    border: 1px solid #e5e7eb;
    border-radius: 0.5rem;
    background: #f9fafb;
    display: inline-block;
}

/* Slideshow Settings Styles */
.settings-description {
    color: #64748b;
    margin-bottom: 2rem;
    font-size: 0.875rem;
}

.current-slideshow {
    margin-bottom: 2rem;
}

.current-slideshow h4 {
    font-size: 1rem;
    font-weight: 600;
    color: #374151;
    margin-bottom: 1rem;
}

.slideshow-images-list {
    display: flex;
    flex-direction: column;
    gap: 1rem;
}

.slideshow-image-item {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    border: 1px solid #e5e7eb;
    border-radius: 0.5rem;
    background: #f9fafb;
}

.image-preview img {
    border-radius: 0.25rem;
}

.image-details {
    flex: 1;
}

.image-details strong {
    display: block;
    color: #1f2937;
    margin-bottom: 0.25rem;
}

.image-details p {
    color: #64748b;
    font-size: 0.875rem;
    margin: 0;
}

.image-actions {
    display: flex;
    gap: 0.5rem;
}

.btn-sm {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
}

.add-slideshow-form {
    border-top: 1px solid #e5e7eb;
    padding-top: 2rem;
}

.add-slideshow-form h4 {
    font-size: 1rem;
    font-weight: 600;
    color: #374151;
    margin-bottom: 1.5rem;
}

.upload-field,
.existing-field,
.url-field {
    transition: all 0.3s ease;
}
</style>

<script>
function toggleUploadFields() {
    const source = document.getElementById('upload_source').value;
    const uploadField = document.getElementById('upload_field');
    const existingField = document.getElementById('existing_field');
    const urlField = document.getElementById('url_field');
    const imageFile = document.getElementById('image_file');
    const existingImage = document.getElementById('existing_image');
    const imageUrl = document.getElementById('image_url');

    // Hide all fields first
    uploadField.style.display = 'none';
    existingField.style.display = 'none';
    urlField.style.display = 'none';

    // Remove required attributes
    imageFile.removeAttribute('required');
    existingImage.removeAttribute('required');
    imageUrl.removeAttribute('required');

    // Show selected field and make it required
    switch(source) {
        case 'upload':
            uploadField.style.display = 'block';
            imageFile.setAttribute('required', 'required');
            break;
        case 'existing':
            existingField.style.display = 'block';
            existingImage.setAttribute('required', 'required');
            break;
        case 'url':
            urlField.style.display = 'block';
            imageUrl.setAttribute('required', 'required');
            break;
    }
}

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

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