<?php
/**
 * Badge Settings Page
 * Configure event details, logos, and badge design options
 */

require_once 'auth_rbac.php';
require_once '../db_config.php';

// Require admin login and permissions
requirePermission('delegates', 'edit');

$currentPage = 'badges';

$message = '';
$messageType = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        $pdo = getDBConnection();
        
        if ($_POST['action'] === 'update_settings') {
            // Update text settings
            $text_settings = [
                'event_name', 'event_dates', 'event_location',
                'badge_width', 'badge_height', 'qr_code_base_url',
                'badge_background_color', 'badge_text_color', 'badge_accent_color'
            ];
            
            $stmt = $pdo->prepare("INSERT INTO badge_settings (setting_key, setting_value, setting_type) VALUES (?, ?, 'text') ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = CURRENT_TIMESTAMP");
            
            foreach ($text_settings as $key) {
                if (isset($_POST[$key])) {
                    $stmt->execute([$key, $_POST[$key]]);
                }
            }
            
            // Update boolean settings
            $bool_settings = ['enable_qr_code', 'show_hosting_logo', 'show_partner_logo', 'footer_decoration'];
            $stmt_bool = $pdo->prepare("INSERT INTO badge_settings (setting_key, setting_value, setting_type) VALUES (?, ?, 'boolean') ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = CURRENT_TIMESTAMP");
            
            foreach ($bool_settings as $key) {
                $value = isset($_POST[$key]) ? 'true' : 'false';
                $stmt_bool->execute([$key, $value]);
            }
            
            $message = 'Badge settings updated successfully!';
            $messageType = 'success';
        }
        elseif ($_POST['action'] === 'upload_logo') {
            $logo_type = $_POST['logo_type'];
            $allowed_types = ['event_logo_path', 'university_logo_path', 'partner_logo_path'];
            
            if (!in_array($logo_type, $allowed_types)) {
                throw new Exception('Invalid logo type');
            }
            
            if (!isset($_FILES['logo_file']) || $_FILES['logo_file']['error'] !== UPLOAD_ERR_OK) {
                throw new Exception('No file uploaded or upload error');
            }
            
            $file = $_FILES['logo_file'];
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
            $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            
            if (!in_array($file_extension, $allowed_extensions)) {
                throw new Exception('Invalid file type. Only JPG, PNG, GIF, and SVG are allowed.');
            }
            
            // Check file size (max 5MB)
            if ($file['size'] > 5 * 1024 * 1024) {
                throw new Exception('File size exceeds 5MB limit');
            }
            
            // Generate unique filename
            $filename = $logo_type . '_' . time() . '.' . $file_extension;
            $upload_path = __DIR__ . '/../uploads/badges/logos/' . $filename;
            
            if (!move_uploaded_file($file['tmp_name'], $upload_path)) {
                throw new Exception('Failed to save uploaded file');
            }
            
            // Update database
            $relative_path = 'uploads/badges/logos/' . $filename;
            $stmt = $pdo->prepare("INSERT INTO badge_settings (setting_key, setting_value, setting_type) VALUES (?, ?, 'image') ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = CURRENT_TIMESTAMP");
            $stmt->execute([$logo_type, $relative_path]);
            
            $message = 'Logo uploaded successfully!';
            $messageType = 'success';
        }
        
    } catch (Exception $e) {
        $message = 'Error: ' . $e->getMessage();
        $messageType = 'error';
    }
}

// Get current settings
try {
    $pdo = getDBConnection();
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM badge_settings");
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
} catch (Exception $e) {
    $error = "Database error: " . $e->getMessage();
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Badge Settings - XChange Admin</title>
    <?php include '../includes/favicon.php'; ?>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../styles.css">
    <link rel="stylesheet" href="admin.css">
    <style>
        .settings-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .settings-section {
            background: white;
            border-radius: 12px;
            box-shadow: var(--shadow);
            padding: 1.5rem;
        }
        
        .settings-section h2 {
            margin: 0 0 1.5rem 0;
            color: #2c3e50;
            font-size: 1.25rem;
            font-weight: 600;
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 0.75rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #374151;
            font-size: 14px;
        }
        
        .form-group input[type="text"],
        .form-group input[type="url"],
        .form-group input[type="number"],
        .form-group input[type="color"] {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #d1d5db;
            border-radius: 8px;
            font-size: 14px;
            transition: border-color 0.2s;
        }
        
        .form-group input:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
        
        .form-group small {
            display: block;
            margin-top: 0.25rem;
            color: #6b7280;
            font-size: 12px;
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.75rem;
            background: #f8f9fa;
            border-radius: 8px;
            margin-bottom: 0.75rem;
        }
        
        .checkbox-group input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        
        .checkbox-group label {
            margin: 0;
            cursor: pointer;
            font-weight: 500;
        }
        
        .logo-preview {
            margin-top: 1rem;
            padding: 1rem;
            border: 2px dashed #d1d5db;
            border-radius: 8px;
            text-align: center;
            background: #f9fafb;
        }
        
        .logo-preview img {
            max-width: 200px;
            max-height: 100px;
            object-fit: contain;
        }
        
        .logo-preview.empty {
            color: #6b7280;
            font-style: italic;
        }
        
        .color-picker-group {
            display: grid;
            grid-template-columns: 60px 1fr;
            gap: 0.75rem;
            align-items: center;
        }
        
        .color-picker-group input[type="color"] {
            width: 60px;
            height: 40px;
            padding: 0;
            border: 2px solid #d1d5db;
            cursor: pointer;
        }
        
        .upload-area {
            margin-top: 1rem;
            padding: 1.5rem;
            border: 2px dashed #d1d5db;
            border-radius: 8px;
            text-align: center;
            background: #f9fafb;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .upload-area:hover {
            border-color: #3b82f6;
            background: #eff6ff;
        }
        
        .upload-area input[type="file"] {
            display: none;
        }
    </style>
</head>
<body>
    <?php include 'includes/admin_nav.php'; ?>

    <div class="admin-content">
        <div class="page-header" style="display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h1>⚙️ Badge Settings</h1>
                <p>Configure event details and badge design</p>
            </div>
            <div>
                <a href="badges.php" class="btn btn-secondary">
                    ← Back to Badges
                </a>
            </div>
        </div>

        <?php if (!empty($message)): ?>
            <div class="alert alert-<?php echo $messageType; ?> mb-4"><?php echo htmlspecialchars($message); ?></div>
        <?php endif; ?>

        <form method="POST" id="settingsForm">
            <input type="hidden" name="action" value="update_settings">
            
            <div class="settings-grid">
                <!-- Event Information -->
                <div class="settings-section">
                    <h2>📅 Event Information</h2>
                    
                    <div class="form-group">
                        <label for="event_name">Event Name *</label>
                        <input type="text" id="event_name" name="event_name" required
                               value="<?php echo htmlspecialchars($settings['event_name'] ?? 'Applied HE>X CHANGE'); ?>">
                        <small>Main event title displayed on badge</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="event_dates">Event Dates *</label>
                        <input type="text" id="event_dates" name="event_dates" required
                               value="<?php echo htmlspecialchars($settings['event_dates'] ?? '27-28 FEB 2025'); ?>">
                        <small>E.g., "27-28 FEB 2025"</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="event_location">Event Location *</label>
                        <input type="text" id="event_location" name="event_location" required
                               value="<?php echo htmlspecialchars($settings['event_location'] ?? 'MANILA, PHILIPPINES'); ?>">
                        <small>E.g., "MANILA, PHILIPPINES"</small>
                    </div>
                </div>

                <!-- Badge Dimensions -->
                <div class="settings-section">
                    <h2>📏 Badge Dimensions</h2>
                    
                    <div class="form-group">
                        <label for="badge_width">Badge Width (px) *</label>
                        <input type="number" id="badge_width" name="badge_width" required min="200" max="1000"
                               value="<?php echo htmlspecialchars($settings['badge_width'] ?? '340'); ?>">
                        <small>Recommended: 340px</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="badge_height">Badge Height (px) *</label>
                        <input type="number" id="badge_height" name="badge_height" required min="200" max="1500"
                               value="<?php echo htmlspecialchars($settings['badge_height'] ?? '500'); ?>">
                        <small>Recommended: 500px</small>
                    </div>
                </div>

                <!-- QR Code Settings -->
                <div class="settings-section">
                    <h2>📱 QR Code Settings</h2>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" id="enable_qr_code" name="enable_qr_code"
                               <?php echo ($settings['enable_qr_code'] ?? 'true') === 'true' ? 'checked' : ''; ?>>
                        <label for="enable_qr_code">Enable QR Code on Badges</label>
                    </div>
                    
                    <div class="form-group">
                        <label for="qr_code_base_url">QR Code Base URL</label>
                        <input type="url" id="qr_code_base_url" name="qr_code_base_url"
                               value="<?php echo htmlspecialchars($settings['qr_code_base_url'] ?? ''); ?>"
                               placeholder="https://yoursite.com/verify/">
                        <small>Leave empty to use registration number only</small>
                    </div>
                </div>

                <!-- Display Options -->
                <div class="settings-section">
                    <h2>👁️ Display Options</h2>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" id="show_hosting_logo" name="show_hosting_logo"
                               <?php echo ($settings['show_hosting_logo'] ?? 'true') === 'true' ? 'checked' : ''; ?>>
                        <label for="show_hosting_logo">Show Hosting University Logo</label>
                    </div>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" id="show_partner_logo" name="show_partner_logo"
                               <?php echo ($settings['show_partner_logo'] ?? 'true') === 'true' ? 'checked' : ''; ?>>
                        <label for="show_partner_logo">Show Partner Logo</label>
                    </div>
                    
                    <div class="checkbox-group">
                        <input type="checkbox" id="footer_decoration" name="footer_decoration"
                               <?php echo ($settings['footer_decoration'] ?? 'true') === 'true' ? 'checked' : ''; ?>>
                        <label for="footer_decoration">Show Footer Decoration</label>
                    </div>
                </div>
            </div>

            <!-- Color Settings -->
            <div class="settings-section" style="margin-bottom: 2rem;">
                <h2>🎨 Color Scheme</h2>
                
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 1.5rem;">
                    <div class="form-group">
                        <label for="badge_background_color">Background Color</label>
                        <div class="color-picker-group">
                            <input type="color" id="badge_background_color" name="badge_background_color"
                                   value="<?php echo htmlspecialchars($settings['badge_background_color'] ?? '#ffffff'); ?>">
                            <input type="text" readonly
                                   value="<?php echo htmlspecialchars($settings['badge_background_color'] ?? '#ffffff'); ?>"
                                   style="text-transform: uppercase;">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="badge_text_color">Text Color</label>
                        <div class="color-picker-group">
                            <input type="color" id="badge_text_color" name="badge_text_color"
                                   value="<?php echo htmlspecialchars($settings['badge_text_color'] ?? '#000000'); ?>">
                            <input type="text" readonly
                                   value="<?php echo htmlspecialchars($settings['badge_text_color'] ?? '#000000'); ?>"
                                   style="text-transform: uppercase;">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="badge_accent_color">Accent Color</label>
                        <div class="color-picker-group">
                            <input type="color" id="badge_accent_color" name="badge_accent_color"
                                   value="<?php echo htmlspecialchars($settings['badge_accent_color'] ?? '#6B9F3E'); ?>">
                            <input type="text" readonly
                                   value="<?php echo htmlspecialchars($settings['badge_accent_color'] ?? '#6B9F3E'); ?>"
                                   style="text-transform: uppercase;">
                        </div>
                    </div>
                </div>
            </div>

            <div style="text-align: right; margin-bottom: 2rem;">
                <button type="submit" class="btn btn-primary">
                    💾 Save Settings
                </button>
            </div>
        </form>

        <!-- Logo Upload Section -->
        <div class="settings-grid">
            <!-- Event Logo -->
            <div class="settings-section">
                <h2>🎯 Event Logo</h2>
                <form method="POST" enctype="multipart/form-data" id="eventLogoForm">
                    <input type="hidden" name="action" value="upload_logo">
                    <input type="hidden" name="logo_type" value="event_logo_path">
                    
                    <div class="logo-preview <?php echo empty($settings['event_logo_path']) ? 'empty' : ''; ?>">
                        <?php if (!empty($settings['event_logo_path'])): ?>
                            <img src="../<?php echo htmlspecialchars($settings['event_logo_path']); ?>" alt="Event Logo">
                        <?php else: ?>
                            No logo uploaded
                        <?php endif; ?>
                    </div>
                    
                    <div class="upload-area" onclick="document.getElementById('event_logo_file').click()">
                        <input type="file" id="event_logo_file" name="logo_file" accept="image/*" onchange="this.form.submit()">
                        <p style="margin: 0; color: #6b7280;">
                            📁 Click to upload event logo<br>
                            <small>JPG, PNG, GIF, SVG (Max 5MB)</small>
                        </p>
                    </div>
                </form>
            </div>

            <!-- Hosting University Logo -->
            <div class="settings-section">
                <h2>🏛️ Hosting University Logo</h2>
                <form method="POST" enctype="multipart/form-data" id="universityLogoForm">
                    <input type="hidden" name="action" value="upload_logo">
                    <input type="hidden" name="logo_type" value="university_logo_path">
                    
                    <div class="logo-preview <?php echo empty($settings['university_logo_path']) ? 'empty' : ''; ?>">
                        <?php if (!empty($settings['university_logo_path'])): ?>
                            <img src="../<?php echo htmlspecialchars($settings['university_logo_path']); ?>" alt="University Logo">
                        <?php else: ?>
                            No logo uploaded
                        <?php endif; ?>
                    </div>
                    
                    <div class="upload-area" onclick="document.getElementById('university_logo_file').click()">
                        <input type="file" id="university_logo_file" name="logo_file" accept="image/*" onchange="this.form.submit()">
                        <p style="margin: 0; color: #6b7280;">
                            📁 Click to upload university logo<br>
                            <small>JPG, PNG, GIF, SVG (Max 5MB)</small>
                        </p>
                    </div>
                </form>
            </div>

            <!-- Partner Logo -->
            <div class="settings-section">
                <h2>🤝 Partner Logo</h2>
                <form method="POST" enctype="multipart/form-data" id="partnerLogoForm">
                    <input type="hidden" name="action" value="upload_logo">
                    <input type="hidden" name="logo_type" value="partner_logo_path">
                    
                    <div class="logo-preview <?php echo empty($settings['partner_logo_path']) ? 'empty' : ''; ?>">
                        <?php if (!empty($settings['partner_logo_path'])): ?>
                            <img src="../<?php echo htmlspecialchars($settings['partner_logo_path']); ?>" alt="Partner Logo">
                        <?php else: ?>
                            No logo uploaded
                        <?php endif; ?>
                    </div>
                    
                    <div class="upload-area" onclick="document.getElementById('partner_logo_file').click()">
                        <input type="file" id="partner_logo_file" name="logo_file" accept="image/*" onchange="this.form.submit()">
                        <p style="margin: 0; color: #6b7280;">
                            📁 Click to upload partner logo<br>
                            <small>JPG, PNG, GIF, SVG (Max 5MB)</small>
                        </p>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Update color text fields when color picker changes
        document.querySelectorAll('input[type="color"]').forEach(colorInput => {
            colorInput.addEventListener('change', function() {
                const textInput = this.nextElementSibling;
                if (textInput && textInput.tagName === 'INPUT') {
                    textInput.value = this.value.toUpperCase();
                }
            });
        });
    </script>

    <?php include 'includes/footer.php'; ?>
</body>
</html>


