<?php
/**
 * Admin - Link Management
 * Manage all frontend button links (Learn More, Explore, Get Started, etc.)
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'Link Management';

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

// Predefined link keys that can be managed
$link_keys = [
    'hero_cta_button' => ['label' => 'Hero CTA Button', 'default' => 'https://wa.me/916388758325?text=Hi..', 'description' => 'Main hero section call-to-action button'],
    'navbar_get_started' => ['label' => 'Navbar Get Started', 'default' => BASE_URL . 'register.php', 'description' => 'Get Started button in navigation'],
    'services_learn_more' => ['label' => 'Services Learn More', 'default' => BASE_URL . 'services.php', 'description' => 'Learn More button on services section'],
    'software_explore' => ['label' => 'Software Explore', 'default' => BASE_URL . 'software.php', 'description' => 'Explore button on software section'],
    'plans_view_all' => ['label' => 'View All Plans', 'default' => BASE_URL . 'plans.php', 'description' => 'View All Plans button'],
    'cta_get_started' => ['label' => 'CTA Get Started', 'default' => BASE_URL . 'register.php', 'description' => 'Get Started in CTA sections'],
    'cta_contact' => ['label' => 'CTA Contact Us', 'default' => BASE_URL . 'contact.php', 'description' => 'Contact Us button'],
    'footer_whatsapp' => ['label' => 'Footer WhatsApp', 'default' => 'https://wa.me/916388758325', 'description' => 'WhatsApp link in footer'],
    'blog_read_more' => ['label' => 'Blog Read More', 'default' => BASE_URL . 'blog.php', 'description' => 'Read More on blog section'],
    'support_link' => ['label' => 'Support Link', 'default' => BASE_URL . 'support.php', 'description' => 'Help/Support link'],
];

// Get current links
$links = [];
try {
    $stmt = db()->query("SELECT * FROM site_settings WHERE setting_key LIKE 'link_%' OR setting_key IN ('" . implode("','", array_keys($link_keys)) . "')");
    while ($row = $stmt->fetch()) {
        $links[$row['setting_key']] = $row['setting_value'];
    }
} catch (PDOException $e) {
    $error = 'Database error: ' . $e->getMessage();
}

// Save links
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid security token';
    } else {
        try {
            foreach ($link_keys as $key => $config) {
                $value = $_POST[$key] ?? $config['default'];
                
                // Check if exists
                $check = db()->prepare("SELECT id FROM site_settings WHERE setting_key = ?");
                $check->execute([$key]);
                
                if ($check->fetch()) {
                    $stmt = db()->prepare("UPDATE site_settings SET setting_value = ? WHERE setting_key = ?");
                    $stmt->execute([$value, $key]);
                } else {
                    $stmt = db()->prepare("INSERT INTO site_settings (setting_key, setting_value, setting_group) VALUES (?, ?, 'links')");
                    $stmt->execute([$key, $value]);
                }
            }
            
            // Refresh links
            $stmt = db()->query("SELECT * FROM site_settings WHERE setting_key LIKE 'link_%' OR setting_key IN ('" . implode("','", array_keys($link_keys)) . "')");
            $links = [];
            while ($row = $stmt->fetch()) {
                $links[$row['setting_key']] = $row['setting_value'];
            }
            
            $success = 'Links updated successfully';
        } catch (PDOException $e) {
            $error = 'Failed to save links: ' . $e->getMessage();
        }
    }
}

$csrf_token = generate_csrf_token();

include __DIR__ . '/includes/header.php';
?>

<style>
.link-card {
    transition: all 0.2s ease;
}
.link-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;
}
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="fw-bold mb-1">Link Management</h2>
        <p class="text-muted mb-0">Manage all frontend button links and call-to-action URLs</p>
    </div>
    <a href="dashboard.php" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-2"></i>Back to Dashboard
    </a>
</div>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="bi bi-check-circle-fill me-2"></i><?php echo $success; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>
<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-circle-fill me-2"></i><?php echo $error; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="fw-bold mb-0"><i class="bi bi-link-45deg text-primary me-2"></i>Manage Frontend Links</h5>
    </div>
    <div class="card-body p-4">
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            
            <div class="row g-4">
                <?php foreach ($link_keys as $key => $config): 
                    $current_value = $links[$key] ?? $config['default'];
                ?>
                <div class="col-md-6">
                    <div class="card link-card border h-100">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <label class="form-label fw-bold mb-0"><?php echo $config['label']; ?></label>
                                <span class="badge bg-light text-dark border"><?php echo $key; ?></span>
                            </div>
                            <p class="text-muted small mb-3"><?php echo $config['description']; ?></p>
                            <input type="text" name="<?php echo $key; ?>" class="form-control" value="<?php echo $current_value; ?>" placeholder="<?php echo $config['default']; ?>">
                            <small class="text-muted">Default: <?php echo $config['default']; ?></small>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div class="mt-4 d-flex gap-3">
                <button type="submit" class="btn btn-primary btn-lg">
                    <i class="bi bi-save me-2"></i>Save All Links
                </button>
                <button type="reset" class="btn btn-outline-secondary btn-lg">
                    <i class="bi bi-arrow-counterclockwise me-2"></i>Reset Changes
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Helper Info -->
<div class="card border-0 shadow-sm mt-4 bg-light">
    <div class="card-body p-4">
        <h5 class="fw-bold mb-3"><i class="bi bi-info-circle text-info me-2"></i>How to Use</h5>
        <div class="row">
            <div class="col-md-6">
                <h6 class="fw-bold">External Links</h6>
                <p class="text-muted small">For external websites, use full URLs starting with https://<br>
                Example: <code>https://wa.me/916388758325</code></p>
            </div>
            <div class="col-md-6">
                <h6 class="fw-bold">Internal Links</h6>
                <p class="text-muted small">For internal pages, you can use relative paths or BASE_URL constant<br>
                Example: <code>/hostxolo/services.php</code> or <code>https://yoursite.com/services.php</code></p>
            </div>
        </div>
        <div class="alert alert-warning mb-0 mt-3">
            <i class="bi bi-exclamation-triangle me-2"></i>
            <strong>Note:</strong> Changes take effect immediately. Make sure to test all links after updating.
        </div>
    </div>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
