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

// Enhanced error reporting
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

try {
    // Initialize database connection using the config
    $pdo = new PDO(
        "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset={$dbConfig['charset']}",
        $dbConfig['username'],
        $dbConfig['password'],
        $dbConfig['options']
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    error_log('Database connection failed: ' . $e->getMessage());
    die('We\'re experiencing technical difficulties. Please try again later.');
}

// Handle update form submission
$success_message = '';
$error_message = '';
$debug_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['update']) || isset($_POST['id']))) {
    $debug_message = "Form submitted - POST data received";
    
    $id = $_POST['id'] ?? '';
    $seo_title = $_POST['seo_title'] ?? '';
    $seo_description = $_POST['seo_description'] ?? '';
    $content = $_POST['content'] ?? '';

    if (empty($id)) {
        $error_message = "Error: No ID provided for update.";
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE city_service SET seo_title=?, seo_description=?, content=? WHERE id=?");
            $result = $stmt->execute([$seo_title, $seo_description, $content, $id]);
            
            if ($result) {
                $rowsAffected = $stmt->rowCount();
                if ($rowsAffected > 0) {
                    $success_message = "✅ Record updated successfully! (ID: $id, Rows affected: $rowsAffected)";
                } else {
                    $error_message = "No rows were updated. Record with ID $id may not exist.";
                }
            } else {
                $error_message = "Error executing update query.";
            }
        } catch (Exception $e) {
            $error_message = "Database error: " . $e->getMessage();
        }
    }
}

// Handle search and filters
$search = $_GET['search'] ?? '';
$city_filter = $_GET['city'] ?? '';
$service_filter = $_GET['service'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 10;
$offset = ($page - 1) * $per_page;

// Build query with filters
$where_conditions = [];
$params = [];

if ($search) {
    $where_conditions[] = "(c.name LIKE ? OR s.name LIKE ? OR cs.seo_title LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($city_filter) {
    $where_conditions[] = "c.slug = ?";
    $params[] = $city_filter;
}

if ($service_filter) {
    $where_conditions[] = "s.slug = ?";
    $params[] = $service_filter;
}

$where_clause = $where_conditions ? "WHERE " . implode(" AND ", $where_conditions) : "";

// Get total count for pagination
$count_stmt = $pdo->prepare("
    SELECT COUNT(*) as total
    FROM city_service cs
    JOIN cities c ON cs.city_id = c.id
    JOIN services s ON cs.service_id = s.id
    $where_clause
");
$count_stmt->execute($params);
$total_records = $count_stmt->fetch()['total'];
$total_pages = ceil($total_records / $per_page);

// Fetch filtered results with pagination
$stmt = $pdo->prepare("
    SELECT cs.id, c.name AS city, c.slug as city_slug, s.name AS service, s.slug as service_slug, 
           cs.seo_title, cs.seo_description, cs.content, cs.updated_at
    FROM city_service cs
    JOIN cities c ON cs.city_id = c.id
    JOIN services s ON cs.service_id = s.id
    $where_clause
    ORDER BY c.name, s.name
    LIMIT $per_page OFFSET $offset
");
$stmt->execute($params);
$rows = $stmt->fetchAll();

// Get all cities and services for filters
$cities = $pdo->query("SELECT slug, name FROM cities ORDER BY name")->fetchAll();
$services = $pdo->query("SELECT slug, name FROM services ORDER BY name")->fetchAll();

// Get statistics
$stats = [
    'total_cities' => $pdo->query("SELECT COUNT(*) FROM cities")->fetchColumn(),
    'total_services' => $pdo->query("SELECT COUNT(*) FROM services")->fetchColumn(),
    'total_combinations' => $pdo->query("SELECT COUNT(*) FROM city_service")->fetchColumn(),
    'updated_today' => $pdo->query("SELECT COUNT(*) FROM city_service WHERE DATE(updated_at) = CURDATE()")->fetchColumn()
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Content Management | Finggu Infotech Admin</title>
    
    <!-- Fonts & Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            overflow-x: hidden;
        }

        /* Sidebar */
        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            width: 280px;
            height: 100vh;
            background: linear-gradient(180deg, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.6) 100%);
            backdrop-filter: blur(20px);
            border-right: 1px solid rgba(255, 255, 255, 0.1);
            z-index: 1000;
            transition: all 0.3s ease;
        }

        .sidebar-header {
            padding: 2rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .logo {
            display: flex;
            align-items: center;
            color: white;
            text-decoration: none;
        }

        .logo-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #ff6b6b, #ee5a24);
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            font-size: 1.5rem;
        }

        .nav-menu {
            padding: 1rem;
        }

        .nav-item {
            display: flex;
            align-items: center;
            padding: 1rem 1.5rem;
            color: rgba(255, 255, 255, 0.7);
            text-decoration: none;
            border-radius: 12px;
            margin-bottom: 0.5rem;
            transition: all 0.3s ease;
        }

        .nav-item:hover, .nav-item.active {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            transform: translateX(5px);
        }

        .nav-item i {
            width: 20px;
            margin-right: 1rem;
            font-size: 1.1rem;
        }

        /* Main Content */
        .main-content {
            margin-left: 280px;
            padding: 2rem;
            min-height: 100vh;
        }

        /* Header */
        .header {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            padding: 1.5rem 2rem;
            margin-bottom: 2rem;
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
        }

        .header h1 {
            font-size: 2.5rem;
            font-weight: 800;
            margin-bottom: 0.5rem;
            background: linear-gradient(135deg, #fff, #f1c40f);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        /* Messages */
        .message {
            padding: 1rem 1.5rem;
            border-radius: 15px;
            margin-bottom: 1.5rem;
            border: 1px solid;
            backdrop-filter: blur(10px);
        }

        .message.success {
            background: rgba(46, 204, 113, 0.1);
            border-color: rgba(46, 204, 113, 0.3);
            color: #2ecc71;
        }

        .message.error {
            background: rgba(231, 76, 60, 0.1);
            border-color: rgba(231, 76, 60, 0.3);
            color: #e74c3c;
        }

        .message.debug {
            background: rgba(241, 196, 15, 0.1);
            border-color: rgba(241, 196, 15, 0.3);
            color: #f1c40f;
        }

        /* Stats Cards */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 1.5rem;
            text-align: center;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.3);
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 30px 60px rgba(0, 0, 0, 0.2);
        }

        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1rem;
            font-size: 1.5rem;
            color: white;
        }

        .stat-icon.cities { background: linear-gradient(135deg, #667eea, #764ba2); }
        .stat-icon.services { background: linear-gradient(135deg, #f093fb, #f5576c); }
        .stat-icon.combinations { background: linear-gradient(135deg, #4facfe, #00f2fe); }
        .stat-icon.updated { background: linear-gradient(135deg, #43e97b, #38f9d7); }

        .stat-value {
            font-size: 2.5rem;
            font-weight: 800;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }

        .stat-label {
            color: #7f8c8d;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.8rem;
            letter-spacing: 1px;
        }

        /* Filter Section */
        .filter-section {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.3);
        }

        .filter-header {
            display: flex;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        .filter-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            color: white;
            font-size: 1.2rem;
        }

        .filter-title {
            font-size: 1.3rem;
            font-weight: 700;
            color: #2c3e50;
        }

        .filter-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
            align-items: end;
        }

        .filter-group {
            display: flex;
            flex-direction: column;
        }

        .filter-label {
            margin-bottom: 0.5rem;
            font-weight: 600;
            color: #2c3e50;
        }

        .filter-input, .filter-select {
            padding: 1rem;
            border: 2px solid #ecf0f1;
            border-radius: 12px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: #fff;
        }

        .filter-input:focus, .filter-select:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .btn {
            padding: 1rem 2rem;
            border: none;
            border-radius: 12px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            justify-content: center;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3);
        }

        .btn-success {
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
        }

        .btn-clear {
            background: linear-gradient(135deg, #95a5a6, #7f8c8d);
            color: white;
        }

        .btn i {
            margin-right: 0.5rem;
        }

        /* Content Table */
        .content-section {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            padding: 2rem;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.3);
            margin-bottom: 2rem;
        }

        .content-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        .content-title {
            display: flex;
            align-items: center;
            font-size: 1.3rem;
            font-weight: 700;
            color: #2c3e50;
        }

        .content-count {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.9rem;
            font-weight: 600;
        }

        .content-table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 2rem;
        }

        .content-table th {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            padding: 1rem;
            text-align: left;
            font-weight: 700;
            color: #2c3e50;
            border-bottom: 2px solid #dee2e6;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .content-table td {
            padding: 1.5rem 1rem;
            border-bottom: 1px solid #e9ecef;
            vertical-align: top;
        }

        .content-table tr:hover {
            background: rgba(102, 126, 234, 0.05);
        }

        .city-info {
            display: flex;
            align-items: center;
        }

        .city-avatar {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 700;
            margin-right: 1rem;
        }

        .city-details h4 {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .city-link {
            font-size: 0.8rem;
            color: #667eea;
            text-decoration: none;
        }

        .city-link:hover {
            text-decoration: underline;
        }

        .service-badge {
            display: inline-flex;
            align-items: center;
            background: linear-gradient(135deg, #f093fb, #f5576c);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .service-badge i {
            margin-right: 0.5rem;
        }

        .form-field {
            width: 100%;
            padding: 0.75rem;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 0.9rem;
            transition: all 0.3s ease;
            font-family: inherit;
        }

        .form-field:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        .form-textarea {
            min-height: 100px;
            resize: vertical;
        }

        .btn-save {
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-save:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 0.3);
        }

        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 0.5rem;
            margin-top: 2rem;
        }

        .pagination a, .pagination span {
            padding: 0.75rem 1rem;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .pagination a {
            background: rgba(255, 255, 255, 0.8);
            color: #2c3e50;
            border: 1px solid #e9ecef;
        }

        .pagination a:hover {
            background: #667eea;
            color: white;
            transform: translateY(-2px);
        }

        .pagination .current {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .main-content {
                margin-left: 0;
                padding: 1rem;
            }
            
            .filter-grid {
                grid-template-columns: 1fr;
            }
            
            .content-table {
                font-size: 0.8rem;
            }
            
            .content-table th,
            .content-table td {
                padding: 0.75rem 0.5rem;
            }
        }

        /* Animations */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .animate-fade-in-up {
            animation: fadeInUp 0.6s ease forwards;
        }

        .animate-delay-1 { animation-delay: 0.1s; }
        .animate-delay-2 { animation-delay: 0.2s; }
        .animate-delay-3 { animation-delay: 0.3s; }

        /* Loading States */
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }

        .spinner {
            display: inline-block;
            width: 16px;
            height: 16px;
            border: 2px solid #ffffff;
            border-radius: 50%;
            border-top-color: transparent;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-header">
            <a href="modern-dashboard.php" class="logo">
                <div class="logo-icon">
                    <i class="fas fa-rocket"></i>
                </div>
                <div>
                    <h2 style="font-weight: 800; font-size: 1.3rem;">Finggu Admin</h2>
                    <p style="font-size: 0.8rem; opacity: 0.7;">Control Panel</p>
                </div>
            </a>
        </div>
        
        <nav class="nav-menu">
            <a href="modern-dashboard.php" class="nav-item">
                <i class="fas fa-tachometer-alt"></i>
                <span>Dashboard</span>
            </a>
            <a href="#" class="nav-item active">
                <i class="fas fa-edit"></i>
                <span>Content Management</span>
            </a>
            <a href="modern-manage-cities-services.php" class="nav-item">
                <i class="fas fa-city"></i>
                <span>Cities & Services</span>
            </a>
            <a href="modern-seo-optimizer.php" class="nav-item">
                <i class="fas fa-search"></i>
                <span>SEO Optimizer</span>
            </a>
            <a href="modern-sync-data.php" class="nav-item">
                <i class="fas fa-sync"></i>
                <span>Sync Data</span>
            </a>
            <a href="../" class="nav-item">
                <i class="fas fa-globe"></i>
                <span>View Website</span>
            </a>
            <a href="logout.php" class="nav-item">
                <i class="fas fa-sign-out-alt"></i>
                <span>Logout</span>
            </a>
        </nav>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <div class="header animate-fade-in-up">
            <h1>Content Management ✏️</h1>
            <p style="opacity: 0.9; font-size: 1.1rem;">Edit and optimize your website content for better SEO performance</p>
        </div>

        <!-- Messages -->
        <?php if ($debug_message): ?>
            <div class="message debug animate-fade-in-up">
                <i class="fas fa-bug" style="margin-right: 0.5rem;"></i><?= $debug_message ?>
            </div>
        <?php endif; ?>
        
        <?php if ($success_message): ?>
            <div class="message success animate-fade-in-up">
                <i class="fas fa-check-circle" style="margin-right: 0.5rem;"></i><?= $success_message ?>
            </div>
        <?php endif; ?>

        <?php if ($error_message): ?>
            <div class="message error animate-fade-in-up">
                <i class="fas fa-exclamation-circle" style="margin-right: 0.5rem;"></i><?= $error_message ?>
            </div>
        <?php endif; ?>

        <!-- Statistics -->
        <div class="stats-grid animate-fade-in-up animate-delay-1">
            <div class="stat-card">
                <div class="stat-icon cities">
                    <i class="fas fa-city"></i>
                </div>
                <div class="stat-value"><?= $stats['total_cities'] ?></div>
                <div class="stat-label">Total Cities</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon services">
                    <i class="fas fa-cogs"></i>
                </div>
                <div class="stat-value"><?= $stats['total_services'] ?></div>
                <div class="stat-label">Total Services</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon combinations">
                    <i class="fas fa-file-alt"></i>
                </div>
                <div class="stat-value"><?= $stats['total_combinations'] ?></div>
                <div class="stat-label">Total Pages</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon updated">
                    <i class="fas fa-clock"></i>
                </div>
                <div class="stat-value"><?= $stats['updated_today'] ?></div>
                <div class="stat-label">Updated Today</div>
            </div>
        </div>

        <!-- Filters -->
        <div class="filter-section animate-fade-in-up animate-delay-2">
            <div class="filter-header">
                <div class="filter-icon">
                    <i class="fas fa-filter"></i>
                </div>
                <div class="filter-title">Search & Filter Content</div>
            </div>
            <form method="GET" class="filter-grid">
                <div class="filter-group">
                    <label class="filter-label">Search</label>
                    <input type="text" name="search" value="<?= htmlspecialchars($search) ?>" 
                           placeholder="Search city, service, or title..." class="filter-input">
                </div>
                <div class="filter-group">
                    <label class="filter-label">City</label>
                    <select name="city" class="filter-select">
                        <option value="">All Cities</option>
                        <?php foreach ($cities as $city): ?>
                            <option value="<?= $city['slug'] ?>" <?= $city_filter === $city['slug'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($city['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <label class="filter-label">Service</label>
                    <select name="service" class="filter-select">
                        <option value="">All Services</option>
                        <?php foreach ($services as $service): ?>
                            <option value="<?= $service['slug'] ?>" <?= $service_filter === $service['slug'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($service['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="filter-group">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search"></i>Filter Results
                    </button>
                </div>
                <div class="filter-group">
                    <a href="?" class="btn btn-clear">
                        <i class="fas fa-times"></i>Clear Filters
                    </a>
                </div>
            </form>
        </div>

        <!-- Content Table -->
        <div class="content-section animate-fade-in-up animate-delay-3">
            <div class="content-header">
                <div class="content-title">
                    <i class="fas fa-table" style="margin-right: 0.5rem; color: #667eea;"></i>
                    Content Management
                </div>
                <div class="content-count">
                    Showing <?= count($rows) ?> of <?= $total_records ?> records
                </div>
            </div>

            <?php if (empty($rows)): ?>
                <div style="text-align: center; padding: 3rem; color: #7f8c8d;">
                    <i class="fas fa-search" style="font-size: 3rem; margin-bottom: 1rem; opacity: 0.3;"></i>
                    <h3 style="margin-bottom: 0.5rem;">No results found</h3>
                    <p>Try adjusting your search criteria or filters</p>
                    <a href="?" class="btn btn-primary" style="margin-top: 1rem;">
                        <i class="fas fa-refresh"></i>Clear Filters
                    </a>
                </div>
            <?php else: ?>
                <div style="overflow-x: auto;">
                    <table class="content-table">
                        <thead>
                            <tr>
                                <th>City & Service</th>
                                <th>SEO Title</th>
                                <th>SEO Description</th>
                                <th>Content</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($rows as $index => $row): ?>
                            <tr>
                                <form method="POST" id="form-<?= $row['id'] ?>">
                                    <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                    <td>
                                        <div class="city-info">
                                            <div class="city-avatar">
                                                <?= strtoupper(substr($row['city'], 0, 2)) ?>
                                            </div>
                                            <div class="city-details">
                                                <h4><?= htmlspecialchars($row['city']) ?></h4>
                                                <div class="service-badge">
                                                    <i class="fas fa-cog"></i>
                                                    <?= htmlspecialchars($row['service']) ?>
                                                </div>
                                                <a href="/sudarsha_finggu_html_1/<?= $row['city_slug'] ?>/<?= $row['service_slug'] ?>/" 
                                                   target="_blank" class="city-link">
                                                    <i class="fas fa-external-link-alt"></i> View Live Page
                                                </a>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <input type="text" name="seo_title" value="<?= htmlspecialchars($row['seo_title']) ?>" 
                                               class="form-field" placeholder="Enter SEO title...">
                                    </td>
                                    <td>
                                        <textarea name="seo_description" class="form-field form-textarea" 
                                                  placeholder="Enter SEO description..."><?= htmlspecialchars($row['seo_description']) ?></textarea>
                                    </td>
                                    <td>
                                        <textarea name="content" class="form-field form-textarea" 
                                                  placeholder="Enter page content..."><?= htmlspecialchars($row['content']) ?></textarea>
                                    </td>
                                    <td>
                                        <button type="submit" name="update" value="1" class="btn-save no-loading">
                                            <i class="fas fa-save"></i> Save Changes
                                        </button>
                                    </td>
                                </form>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="pagination">
                        <?php if ($page > 1): ?>
                            <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">
                                <i class="fas fa-chevron-left"></i> Previous
                            </a>
                        <?php endif; ?>

                        <?php for ($i = max(1, $page - 2); $i <= min($total_pages, $page + 2); $i++): ?>
                            <?php if ($i == $page): ?>
                                <span class="current"><?= $i ?></span>
                            <?php else: ?>
                                <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>"><?= $i ?></a>
                            <?php endif; ?>
                        <?php endfor; ?>

                        <?php if ($page < $total_pages): ?>
                            <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">
                                Next <i class="fas fa-chevron-right"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>
    </div>

    <script>
        // Enhanced form submission with loading states
        document.querySelectorAll('form[id^="form-"]').forEach(form => {
            form.addEventListener('submit', function(e) {
                const button = this.querySelector('button[type="submit"]');
                if (button && !button.classList.contains('no-loading')) {
                    const originalHTML = button.innerHTML;
                    button.innerHTML = '<span class="spinner"></span> Saving...';
                    button.disabled = true;
                    
                    // Re-enable after 10 seconds (fallback)
                    setTimeout(() => {
                        button.innerHTML = originalHTML;
                        button.disabled = false;
                    }, 10000);
                }
            });
        });

        // Auto-save functionality (optional)
        let autoSaveTimeout;
        document.querySelectorAll('.form-field').forEach(field => {
            field.addEventListener('input', function() {
                clearTimeout(autoSaveTimeout);
                autoSaveTimeout = setTimeout(() => {
                    // Could implement auto-save here
                    console.log('Auto-save triggered for field:', this.name);
                }, 2000);
            });
        });

        // Smooth scrolling for pagination
        document.querySelectorAll('.pagination a').forEach(link => {
            link.addEventListener('click', function(e) {
                // Add loading state to pagination
                this.style.opacity = '0.6';
                this.style.pointerEvents = 'none';
            });
        });

        // Character count for textareas
        document.querySelectorAll('textarea[name="seo_description"]').forEach(textarea => {
            const maxLength = 160;
            const counter = document.createElement('div');
            counter.style.cssText = 'font-size: 0.7rem; color: #7f8c8d; margin-top: 0.25rem; text-align: right;';
            textarea.parentNode.appendChild(counter);
            
            function updateCounter() {
                const length = textarea.value.length;
                counter.textContent = `${length}/${maxLength} characters`;
                counter.style.color = length > maxLength ? '#e74c3c' : '#7f8c8d';
            }
            
            textarea.addEventListener('input', updateCounter);
            updateCounter();
        });
    </script>
</body>
</html>