<?php
// --- LOGIC BLOCK: All PHP processing must happen before any HTML is sent ---
require_once '../includes/db.php';

// Check for admin login session
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../login.php");
    exit;
}

$message = '';
// Handle form submission for both regular save and AJAX preview save
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['settings'])) {
    
    $settings_to_save = $_POST['settings'];

    foreach ($settings_to_save as $name => $value) {
        $stmt = $conn->prepare("INSERT INTO site_settings (setting_name, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        $stmt->bind_param("sss", $name, $value, $value);
        $stmt->execute();
    }
    
    // If this is an AJAX save from a preview button, return a JSON success message and stop.
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        header('Content-Type: application/json');
        echo json_encode(['success' => true]);
        exit();
    }

    $message = '<div class="alert alert-success">Ticket settings updated successfully!</div>';
}

// Fetch all current settings for displaying in the form
$result = $conn->query("SELECT * FROM site_settings");
$settings = [];
while ($row = $result->fetch_assoc()) {
    $settings[$row['setting_name']] = $row['setting_value'];
}

// --- PRESENTATION BLOCK ---
include 'admin-header.php';
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">Ticket & Voucher Design Editor</h1>
</div>
<?php echo $message; ?>

<form method="POST" id="ticketSettingsForm" action="manage-tickets.php">
    <div class="card shadow-sm mb-4">
        <div class="card-header fw-bold"><i class="bi bi-palette-fill me-2"></i>Global Design Settings</div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Header Color</label>
                    <input type="color" class="form-control form-control-color" name="settings[ticket_header_color]" value="<?php echo htmlspecialchars($settings['ticket_header_color'] ?? '#0d6efd'); ?>">
                    <small class="text-muted">The main color bar at the top of the ticket.</small>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Accent Color</label>
                    <input type="color" class="form-control form-control-color" name="settings[ticket_accent_color]" value="<?php echo htmlspecialchars($settings['ticket_accent_color'] ?? '#198754'); ?>">
                    <small class="text-muted">The color for section headings (e.g., "Booking Details").</small>
                </div>
            </div>
        </div>
        <div class="card-footer text-end">
            <button type="button" class="btn btn-outline-secondary preview-btn" data-type="tour"><i class="bi bi-eye"></i> Preview Tour</button>
            <button type="button" class="btn btn-outline-secondary preview-btn" data-type="hotel"><i class="bi bi-eye"></i> Preview Hotel</button>
            <button type="button" class="btn btn-outline-secondary preview-btn" data-type="flight"><i class="bi bi-eye"></i> Preview Flight</button>
            <button type="button" class="btn btn-outline-secondary preview-btn" data-type="ferry"><i class="bi bi-eye"></i> Preview Ferry</button>
        </div>
    </div>

    <div class="card shadow-sm mb-4">
        <div class="card-header fw-bold"><i class="bi bi-file-text-fill me-2"></i>Custom Text & Notes</div>
        <div class="card-body">
            <ul class="nav nav-tabs" id="textTabs" role="tablist">
                <li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tour-text">Tour</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#hotel-text">Hotel</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#flight-text">Flight</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#ferry-text">Ferry</button></li>
            </ul>
            <div class="tab-content p-3 border border-top-0">
                <div class="tab-pane fade show active" id="tour-text" role="tabpanel">
                    <div class="mb-3"><label class="form-label">Important Notes</label><textarea name="settings[ticket_notes_tour]" class="form-control" rows="3"><?php echo htmlspecialchars($settings['ticket_notes_tour'] ?? ''); ?></textarea></div>
                    <div class="mb-3"><label class="form-label">Footer Text</label><textarea name="settings[ticket_footer_text_tour]" class="form-control" rows="3"><?php echo htmlspecialchars($settings['ticket_footer_text_tour'] ?? ''); ?></textarea></div>
                </div>
                <div class="tab-pane fade" id="hotel-text" role="tabpanel">
                    <div class="mb-3"><label class="form-label">Important Notes</label><textarea name="settings[ticket_notes_hotel]" class="form-control" rows="3"><?php echo htmlspecialchars($settings['ticket_notes_hotel'] ?? ''); ?></textarea></div>
                    <div class="mb-3"><label class="form-label">Footer Text</label><textarea name="settings[ticket_footer_text_hotel]" class="form-control" rows="3"><?php echo htmlspecialchars($settings['ticket_footer_text_hotel'] ?? ''); ?></textarea></div>
                </div>
                <div class="tab-pane fade" id="flight-text" role="tabpanel">
                    <div class="mb-3"><label class="form-label">Important Notes</label><textarea name="settings[ticket_notes_flight]" class="form-control" rows="3"><?php echo htmlspecialchars($settings['ticket_notes_flight'] ?? ''); ?></textarea></div>
                    <div class="mb-3"><label class="form-label">Footer Text</label><textarea name="settings[ticket_footer_text_flight]" class="form-control" rows="3"><?php echo htmlspecialchars($settings['ticket_footer_text_flight'] ?? ''); ?></textarea></div>
                </div>
                 <div class="tab-pane fade" id="ferry-text" role="tabpanel">
                    <div class="mb-3"><label class="form-label">Important Notes</label><textarea name="settings[ticket_notes_ferry]" class="form-control" rows="3"><?php echo htmlspecialchars($settings['ticket_notes_ferry'] ?? ''); ?></textarea></div>
                    <div class="mb-3"><label class="form-label">Footer Text</label><textarea name="settings[ticket_footer_text_ferry]" class="form-control" rows="3"><?php echo htmlspecialchars($settings['ticket_footer_text_ferry'] ?? ''); ?></textarea></div>
                </div>
            </div>
        </div>
    </div>
    
    <button type="submit" name="save_ticket_settings" class="btn btn-primary btn-lg">Save All Settings</button>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('ticketSettingsForm');
    document.querySelectorAll('.preview-btn').forEach(button => {
        button.addEventListener('click', function() {
            const ticketType = this.dataset.type;
            const previewUrl = `preview-ticket.php?type=${ticketType}`;
            
            // This method is more robust against pop-up blockers
            const previewWindow = window.open('', '_blank');
            previewWindow.document.write('Saving settings and generating preview... Please wait.');

            const formData = new FormData(form);
            
            fetch(form.action, {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: formData
            })
            .then(response => {
                if (!response.ok) { throw new Error('Network response was not ok.'); }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // Once settings are saved, redirect the new tab to the preview URL
                    previewWindow.location.href = previewUrl;
                } else {
                    previewWindow.document.write('Could not save settings. Please try again.');
                }
            })
            .catch(error => {
                console.error('Error saving settings:', error);
                previewWindow.document.write('A critical error occurred while saving. Please close this tab and try again.');
            });
        });
    });
});
</script>

<?php include 'admin-footer.php'; ?>
