<?php
require_once '../config.php';

$conn = get_db_connection();
$site_name = get_website_name();
$message = '';
$message_type = '';

// Auto-migrate database: check for description column
$check_col = $conn->query("SHOW COLUMNS FROM page_titles LIKE 'description'");
if ($check_col->num_rows === 0) {
    if ($conn->query("ALTER TABLE page_titles ADD COLUMN description TEXT AFTER title")) {
        $message = 'Database updated: description column added.';
        $message_type = 'success';
    } else {
        $message = 'Database error: ' . $conn->error;
        $message_type = 'danger';
    }
}

// Handle URL scanning
if (isset($_POST['action']) && $_POST['action'] === 'scan') {
    $scanned_data = [];
    $scanned_data['/'] = $site_name . ' - Home';

    // Scan static directories
    $directories = ['about-us', 'contact-us', 'faq', 'our-locations', 'our-work', 'privacy-policy', 'terms-and-conditions', 'online-scheduling'];
    foreach ($directories as $dir) {
        $pretty_name = ucwords(str_replace(['-', '_'], ' ', $dir));
        $scanned_data['/' . $dir] = $pretty_name . ' - ' . $site_name;
    }

    // Scan services from database
    $services_res = $conn->query("SELECT name, slug, url FROM services WHERE slug IS NOT NULL AND slug != ''");
    if ($services_res) {
        while ($row = $services_res->fetch_assoc()) {
            // Add SEO URL (nice URL if exists)
            if (!empty($row['url'])) {
                $url = $row['url'];
                if ($url[0] !== '/')
                    $url = '/' . $url;
                $scanned_data[$url] = $row['name'] . ' - ' . $site_name;
            }
            // Add service.php?slug format as well
            $slug_url = '/service.php?slug=' . $row['slug'];
            $scanned_data[$slug_url] = $row['name'] . ' - ' . $site_name;
        }
    }

    $added_count = 0;
    foreach ($scanned_data as $url => $default_title) {
        $stmt = $conn->prepare("INSERT IGNORE INTO page_titles (url, title, description) VALUES (?, ?, '')");
        $stmt->bind_param("ss", $url, $default_title);
        if ($stmt->execute() && $conn->affected_rows > 0) {
            $added_count++;
        }
        $stmt->close();
    }
    $message = "Scan complete! Added $added_count new URLs with smart labels.";
    $message_type = 'success';
}

// Handle updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'update') {
        $id = intval($_POST['id']);
        $url = trim($_POST['url']);
        $title = trim($_POST['title']);
        $description = trim($_POST['description']);

        if (!empty($url)) {
            $stmt = $conn->prepare("UPDATE page_titles SET url = ?, title = ?, description = ? WHERE id = ?");
            $stmt->bind_param("sssi", $url, $title, $description, $id);
            if ($stmt->execute()) {
                $message = 'SEO settings updated successfully!';
                $message_type = 'success';
            } else {
                $message = 'Error updating: ' . $conn->error;
                $message_type = 'danger';
            }
            $stmt->close();
        }
    } elseif ($_POST['action'] === 'add') {
        $url = trim($_POST['url']);
        $title = trim($_POST['title']);
        $description = trim($_POST['description']);

        if (!empty($url)) {
            $stmt = $conn->prepare("INSERT INTO page_titles (url, title, description) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE title = ?, description = ?");
            $stmt->bind_param("sssss", $url, $title, $description, $title, $description);
            if ($stmt->execute()) {
                $message = 'SEO page added successfully!';
                $message_type = 'success';
            } else {
                $message = 'Error adding: ' . $conn->error;
                $message_type = 'danger';
            }
            $stmt->close();
        }
    } elseif ($_POST['action'] === 'delete') {
        $id = intval($_POST['id']);
        $stmt = $conn->prepare("DELETE FROM page_titles WHERE id = ?");
        $stmt->bind_param("i", $id);
        if ($stmt->execute()) {
            $message = 'SEO settings deleted successfully!';
            $message_type = 'success';
        } else {
            $message = 'Error deleting: ' . $conn->error;
            $message_type = 'danger';
        }
        $stmt->close();
    }
}

$search = isset($_GET['search']) ? trim($_GET['search']) : '';
if (!empty($search)) {
    $search_param = '%' . $search . '%';
    $stmt = $conn->prepare("SELECT * FROM page_titles WHERE url LIKE ? OR title LIKE ? OR description LIKE ? ORDER BY url ASC");
    $stmt->bind_param("sss", $search_param, $search_param, $search_param);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query("SELECT * FROM page_titles ORDER BY url ASC");
}

$page_titles = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $page_titles[] = $row;
    }
}

$page_title = 'SEO Management';
require_once 'includes/admin-header.php';
?>

<div class="row" style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
    <div>
        <p class="text-muted">Manage meta titles and descriptions for all pages to improve search engine visibility.</p>
    </div>
    <div style="display: flex; gap: 10px;">
        <form method="POST" action="">
            <input type="hidden" name="action" value="scan">
            <button type="submit" class="btn btn-secondary">
                <i class="fas fa-sync-alt"></i> Scan for New URLs
            </button>
        </form>
        <button class="btn btn-primary" onclick="toggleAddForm()">
            <i class="fas fa-plus"></i> Add Custom Page
        </button>
    </div>
</div>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div id="addFormCard" class="card" style="display: none; margin-bottom: 20px;">
    <div class="card-header">
        <h2 class="card-title">Add New Page SEO</h2>
    </div>
    <form method="POST" action="" style="padding: 20px;">
        <input type="hidden" name="action" value="add">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
            <div class="form-group">
                <label>URL Path (e.g., /services/cleaning)</label>
                <input type="text" name="url" class="form-control" required placeholder="/my-new-page">
            </div>
            <div class="form-group">
                <label>Meta Title</label>
                <input type="text" name="title" class="form-control" required placeholder="Page Title - Crest Chimney">
            </div>
        </div>
        <div class="form-group" style="margin-bottom: 15px;">
            <label>Meta Description</label>
            <textarea name="description" class="form-control" rows="2"
                placeholder="Brief summary of the page for search results..."></textarea>
        </div>
        <div style="display: flex; gap: 10px;">
            <button type="submit" class="btn btn-primary">Save SEO Settings</button>
            <button type="button" class="btn btn-secondary" onclick="toggleAddForm()">Cancel</button>
        </div>
    </form>
</div>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">All Registered Pages</h2>
        <form method="GET" action="" style="display: flex; gap: 8px;">
            <input type="text" name="search" class="form-control" placeholder="Search by URL or title..."
                value="<?php echo htmlspecialchars($search); ?>" style="width: 250px;">
            <button type="submit" class="btn btn-secondary btn-sm">Search</button>
        </form>
    </div>

    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th style="width: 200px;">URL Path</th>
                    <th>Meta Title & Description</th>
                    <th style="width: 120px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($page_titles)): ?>
                    <tr>
                        <td colspan="3" style="text-align: center; padding: 40px; color: var(--text-muted);">
                            No pages found. Click "Scan" to find available pages.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($page_titles as $page): ?>
                        <tr id="row-<?php echo $page['id']; ?>">
                            <td>
                                <div class="display-mode-<?php echo $page['id']; ?>">
                                    <code style="word-break: break-all;"><?php echo htmlspecialchars($page['url']); ?></code>
                                </div>
                                <input type="text" class="form-control edit-mode-<?php echo $page['id']; ?>"
                                    value="<?php echo htmlspecialchars($page['url']); ?>" style="display: none;">
                            </td>
                            <td>
                                <div class="display-mode-<?php echo $page['id']; ?>">
                                    <strong>
                                        <?php echo htmlspecialchars($page['title'] ?: 'No Title Set'); ?>
                                    </strong><br>
                                    <small class="text-muted">
                                        <?php echo htmlspecialchars($page['description'] ?: 'No description set - using default.'); ?>
                                    </small>
                                </div>
                                <div class="edit-mode-<?php echo $page['id']; ?>"
                                    style="display: none; flex-direction: column; gap: 8px;">
                                    <input type="text" class="form-control" placeholder="Meta Title"
                                        value="<?php echo htmlspecialchars($page['title']); ?>">
                                    <textarea class="form-control" placeholder="Meta Description"
                                        rows="2"><?php echo htmlspecialchars($page['description']); ?></textarea>
                                </div>
                            </td>
                            <td>
                                <div class="display-mode-<?php echo $page['id']; ?>" style="display: flex; gap: 8px;">
                                    <button class="btn btn-secondary btn-sm" onclick="enableEdit(<?php echo $page['id']; ?>)"
                                        title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <form method="POST" action="" style="display: inline;"
                                        onsubmit="return confirm('Are you sure you want to delete SEO settings for this URL?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $page['id']; ?>">
                                        <button type="submit" class="btn btn-danger btn-sm" title="Delete">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </div>
                                <div class="edit-mode-<?php echo $page['id']; ?>" style="display: none; gap: 8px;">
                                    <button class="btn btn-primary btn-sm" onclick="saveEdit(<?php echo $page['id']; ?>)"
                                        title="Save">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <button class="btn btn-secondary btn-sm" onclick="cancelEdit(<?php echo $page['id']; ?>)"
                                        title="Cancel">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<form id="updateForm" method="POST" style="display: none;">
    <input type="hidden" name="action" value="update">
    <input type="hidden" name="id" id="updateId">
    <input type="hidden" name="url" id="updateUrl">
    <input type="hidden" name="title" id="updateTitle">
    <input type="hidden" name="description" id="updateDescription">
</form>

<script>
    function toggleAddForm() {
        const form = document.getElementById('addFormCard');
        form.style.display = form.style.display === 'none' ? 'block' : 'none';
        if (form.style.display === 'block') {
            form.scrollIntoView({ behavior: 'smooth' });
        }
    }

    function enableEdit(id) {
        document.querySelectorAll('.display-mode-' + id).forEach(el => el.style.display = 'none');
        document.querySelectorAll('.edit-mode-' + id).forEach(el => {
            el.style.display = el.nodeName === 'DIV' ? 'flex' : 'block';
        });
    }

    function cancelEdit(id) {
        document.querySelectorAll('.display-mode-' + id).forEach(el => el.style.display = '');
        document.querySelectorAll('.edit-mode-' + id).forEach(el => el.style.display = 'none');
    }

    function saveEdit(id) {
        const row = document.getElementById('row-' + id);
        const urlInput = row.querySelector('input[type="text"].edit-mode-' + id);
        const titleInput = row.querySelector('div.edit-mode-' + id + ' input');
        const descInput = row.querySelector('div.edit-mode-' + id + ' textarea');

        document.getElementById('updateId').value = id;
        document.getElementById('updateUrl').value = urlInput.value;
        document.getElementById('updateTitle').value = titleInput.value;
        document.getElementById('updateDescription').value = descInput.value;
        document.getElementById('updateForm').submit();
    }
</script>

<?php require_once 'includes/admin-footer.php'; ?>