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

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

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

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

            if (!empty($url) && !empty($title)) {
                $stmt = $conn->prepare("INSERT INTO page_titles (url, title) VALUES (?, ?) ON DUPLICATE KEY UPDATE title = ?");
                $stmt->bind_param("sss", $url, $title, $title);
                if ($stmt->execute()) {
                    $message = 'Page title added successfully!';
                    $message_type = 'success';
                } else {
                    $message = 'Error adding page title: ' . $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 = 'Page title deleted successfully!';
                $message_type = 'success';
            } else {
                $message = 'Error deleting page title: ' . $conn->error;
                $message_type = 'danger';
            }
            $stmt->close();
        }
    }
}

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

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

$page_title = 'Page Titles';
require_once 'includes/admin-header.php';
?>

<?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 class="card">
    <div class="card-header">
        <h2 class="card-title">Add New Page Title</h2>
    </div>
    <form method="POST" action="">
        <input type="hidden" name="action" value="add">
        <div class="add-form-row">
            <div class="form-group" style="margin-bottom: 0;">
                <label>URL Path</label>
                <input type="text" name="url" class="form-control" required placeholder="/services/cleaning">
            </div>
            <div class="form-group" style="margin-bottom: 0;">
                <label>Meta Title</label>
                <input type="text" name="title" class="form-control" required
                    placeholder="Service Name - Crest Chimney">
            </div>
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-plus"></i> Add
            </button>
        </div>
    </form>
</div>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Manage Page Titles</h2>
        <form method="GET" action="" style="display: flex; gap: 8px;">
            <input type="text" name="search" class="form-control" placeholder="Search..."
                value="<?php echo htmlspecialchars($search); ?>" style="width: 200px; padding: 8px 12px;">
            <button type="submit" class="btn btn-secondary btn-sm">Search</button>
        </form>
    </div>

    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>URL Path</th>
                    <th>Meta Title</th>
                    <th>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 page titles
                            found.</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><?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']; ?>">
                                    <?php echo htmlspecialchars($page['title']); ?>
                                </div>
                                <input type="text" class="form-control edit-mode-<?php echo $page['id']; ?>"
                                    value="<?php echo htmlspecialchars($page['title']); ?>" style="display: none;">
                            </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']; ?>)">
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <form method="POST" action="" style="display: inline;"
                                        onsubmit="return confirm('Are you sure?');">
                                        <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">
                                            <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']; ?>)">
                                        <i class="fas fa-check"></i>
                                    </button>
                                    <button class="btn btn-secondary btn-sm" onclick="cancelEdit(<?php echo $page['id']; ?>)">
                                        <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">
</form>

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

    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 inputs = row.querySelectorAll('input');
        document.getElementById('updateId').value = id;
        document.getElementById('updateUrl').value = inputs[0].value;
        document.getElementById('updateTitle').value = inputs[1].value;
        document.getElementById('updateForm').submit();
    }
</script>

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