<?php
require_once 'auth.php';

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

// Function to log debug information
function debug_log($message) {
    $log = '[' . date('Y-m-d H:i:s') . '] ' . $message . "\n";
    file_put_contents(__DIR__ . '/debug.log', $log, FILE_APPEND);
}

// Include required files
include '../includes/url-helper.php';
// Centralized PDO connection
require_once __DIR__ . '/../includes/pdo.php';
debug_log('PDO connection established via centralized bootstrap');

debug_log('Script started');

$success_message = '';
$error_message = '';
$debug_message = '';

// Debug: log POST payload
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    debug_log('POST data: ' . print_r($_POST, true));
    $debug_message = 'Received POST action: ' . htmlspecialchars($_POST['action'] ?? '(none)');
    debug_log($debug_message);
}

// Handle Bulk Add Cities
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_cities_bulk') {
    debug_log('Bulk add cities started');
    @set_time_limit(300);
    $citiesBulk = trim($_POST['cities_bulk'] ?? '');
    if ($citiesBulk === '') {
        $error_message = "Please enter one or more city names.";
    } else {
        // Split input on new lines, commas, semicolons
        $rawItems = preg_split('/[\r\n,;]+/', $citiesBulk);
        $uniqueCityNames = [];
        foreach ($rawItems as $item) {
            $name = trim($item);
            if ($name !== '') {
                $uniqueCityNames[$name] = true;
            }
        }

        if (empty($uniqueCityNames)) {
            $error_message = "No valid city names found.";
        } else {
            try {
                $pdo->beginTransaction();
                $addedCount = 0;
                $skippedExisting = 0;
                $totalCombinationsCreated = 0;
                $skippedCities = [];

                // Preload services to create combinations
                $servicesStmt = $pdo->query("SELECT id, name FROM services");
                $services = $servicesStmt->fetchAll();

                // Prepare reusable statements
                $checkCityStmt = $pdo->prepare("SELECT id FROM cities WHERE slug = ?");
                $insertCityStmt = $pdo->prepare("INSERT INTO cities (name, slug) VALUES (?, ?)");
                $insertComboStmt = $pdo->prepare("INSERT INTO city_service (city_id, service_id, seo_title, seo_description, content) VALUES (?, ?, ?, ?, ?)");

                foreach (array_keys($uniqueCityNames) as $cityNameRaw) {
                    $cityName = trim($cityNameRaw);
                    if ($cityName === '') { continue; }
                    $citySlug = cityNameToSlug($cityName);

                    // Check existence
                    $checkCityStmt->execute([$citySlug]);
                    $existing = $checkCityStmt->fetch();
                    if ($existing) {
                        $skippedExisting++;
                        $skippedCities[] = $cityName;
                        continue;
                    }

                    // Insert city
                    $insertCityStmt->execute([$cityName, $citySlug]);
                    $cityId = $pdo->lastInsertId();
                    $addedCount++;

                    // Create combinations for each service
                    $combinationsCreated = 0;
                    foreach ($services as $service) {
                        $serviceName = $service['name'];
                        $seoTitle = "$serviceName in $cityName | Finggu Infotech";
                        $seoDescription = "Professional $serviceName services in $cityName. Get expert digital solutions from Finggu Infotech. Contact us for a free consultation.";
                        $content = "Looking for professional $serviceName services in $cityName? Finggu Infotech offers comprehensive digital solutions tailored to your business needs. Our expert team delivers high-quality results that drive growth and success.\n\nWhy choose us for $serviceName in $cityName?\n- Experienced professionals\n- Proven track record\n- Competitive pricing\n- 24/7 support\n- Custom solutions\n\nContact us today for a free consultation and see how we can help your business grow with our $serviceName services in $cityName.";

                        $insertComboStmt->execute([$cityId, $service['id'], $seoTitle, $seoDescription, $content]);
                        $combinationsCreated++;
                    }
                    $totalCombinationsCreated += $combinationsCreated;
                }

                if ($addedCount > 0) {
                    $pdo->commit();
                    $success_message = "✅ Successfully added $addedCount new cities and created $totalCombinationsCreated service combinations.";
                    if ($skippedExisting > 0) {
                        $success_message .= "<br>⚠️ Skipped $skippedExisting existing cities: " . implode(', ', $skippedCities);
                    }
                } else if ($skippedExisting > 0) {
                    $pdo->rollBack();
                    $error_message = "⚠️ All $skippedExisting cities already exist in database. Skipped cities: " . implode(', ', $skippedCities);
                } else {
                    $pdo->rollBack();
                    $error_message = "❌ No cities were processed. Please check your input.";
                }
            } catch (Exception $e) {
                if ($pdo->inTransaction()) { $pdo->rollBack(); }
                $error_message = "Error adding cities: " . $e->getMessage();
                debug_log('Error: ' . $e->getMessage() . '\n' . $e->getTraceAsString());
            }
        }
    }
}

// Handle Add City
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_city') {
    $cityName = trim($_POST['city_name']);
    
    if (empty($cityName)) {
        $error_message = "City name is required.";
    } else {
        $citySlug = cityNameToSlug($cityName);
        
        try {
            // Check if city already exists
            $checkStmt = $pdo->prepare("SELECT id, name FROM cities WHERE slug = ?");
            $checkStmt->execute([$citySlug]);
            $existingCity = $checkStmt->fetch();
            
            if ($existingCity) {
                $error_message = "City '$cityName' already exists in database as '{$existingCity['name']}'. Skipped adding duplicate.";
            } else {
                // Insert new city
                $insertStmt = $pdo->prepare("INSERT INTO cities (name, slug) VALUES (?, ?)");
                $insertStmt->execute([$cityName, $citySlug]);
                $cityId = $pdo->lastInsertId();
                
                // Create combinations with all existing services
                $servicesStmt = $pdo->query("SELECT id, name FROM services");
                $services = $servicesStmt->fetchAll();
                
                $comboStmt = $pdo->prepare("
                    INSERT INTO city_service (city_id, service_id, seo_title, seo_description, content)
                    VALUES (?, ?, ?, ?, ?)
                ");
                
                $combinationsCreated = 0;
                foreach ($services as $service) {
                    $serviceName = $service['name'];
                    $seoTitle = "$serviceName in $cityName | Finggu Infotech";
                    $seoDescription = "Professional $serviceName services in $cityName. Get expert digital solutions from Finggu Infotech. Contact us for a free consultation.";
                    $content = "Looking for professional $serviceName services in $cityName? Finggu Infotech offers comprehensive digital solutions tailored to your business needs. Our expert team delivers high-quality results that drive growth and success.\n\nWhy choose us for $serviceName in $cityName?\n- Experienced professionals\n- Proven track record\n- Competitive pricing\n- 24/7 support\n- Custom solutions\n\nContact us today for a free consultation and see how we can help your business grow with our $serviceName services in $cityName.";
                    
                    $comboStmt->execute([$cityId, $service['id'], $seoTitle, $seoDescription, $content]);
                    $combinationsCreated++;
                }
                
                $success_message = "✅ City '$cityName' added successfully with $combinationsCreated service combinations!";
            }
        } catch (Exception $e) {
            $error_message = "Error adding city: " . $e->getMessage();
        }
    }
}

// Handle Add Service
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'add_service') {
    $serviceName = trim($_POST['service_name']);
    
    if (empty($serviceName)) {
        $error_message = "Service name is required.";
    } else {
        $serviceSlug = serviceNameToSlug($serviceName);
        
        try {
            // Check if service already exists
            $checkStmt = $pdo->prepare("SELECT id, name FROM services WHERE slug = ?");
            $checkStmt->execute([$serviceSlug]);
            $existingService = $checkStmt->fetch();
            
            if ($existingService) {
                $error_message = "Service '$serviceName' already exists in database as '{$existingService['name']}'. Skipped adding duplicate.";
            } else {
                // Insert new service
                $insertStmt = $pdo->prepare("INSERT INTO services (name, slug) VALUES (?, ?)");
                $insertStmt->execute([$serviceName, $serviceSlug]);
                $serviceId = $pdo->lastInsertId();
                
                // Create combinations with all existing cities
                $citiesStmt = $pdo->query("SELECT id, name FROM cities");
                $cities = $citiesStmt->fetchAll();
                
                $comboStmt = $pdo->prepare("
                    INSERT INTO city_service (city_id, service_id, seo_title, seo_description, content)
                    VALUES (?, ?, ?, ?, ?)
                ");
                
                $combinationsCreated = 0;
                foreach ($cities as $city) {
                    $cityName = $city['name'];
                    $seoTitle = "$serviceName in $cityName | Finggu Infotech";
                    $seoDescription = "Professional $serviceName services in $cityName. Get expert digital solutions from Finggu Infotech. Contact us for a free consultation.";
                    $content = "Looking for professional $serviceName services in $cityName? Finggu Infotech offers comprehensive digital solutions tailored to your business needs. Our expert team delivers high-quality results that drive growth and success.\n\nWhy choose us for $serviceName in $cityName?\n- Experienced professionals\n- Proven track record\n- Competitive pricing\n- 24/7 support\n- Custom solutions\n\nContact us today for a free consultation and see how we can help your business grow with our $serviceName services in $cityName.";
                    
                    $comboStmt->execute([$city['id'], $serviceId, $seoTitle, $seoDescription, $content]);
                    $combinationsCreated++;
                }
                
                $success_message = "✅ Service '$serviceName' added successfully with $combinationsCreated city combinations!";
            }
        } catch (Exception $e) {
            $error_message = "Error adding service: " . $e->getMessage();
        }
    }
}

// Handle Delete City
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_city') {
    $cityId = $_POST['city_id'];
    
    try {
        $stmt = $pdo->prepare("DELETE FROM cities WHERE id = ?");
        $stmt->execute([$cityId]);
        $success_message = "City deleted successfully (along with all its service combinations).";
    } catch (Exception $e) {
        $error_message = "Error deleting city: " . $e->getMessage();
    }
}

// Handle Delete Service
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_service') {
    $serviceId = $_POST['service_id'];
    
    try {
        $stmt = $pdo->prepare("DELETE FROM services WHERE id = ?");
        $stmt->execute([$serviceId]);
        $success_message = "Service deleted successfully (along with all its city combinations).";
    } catch (Exception $e) {
        $error_message = "Error deleting service: " . $e->getMessage();
    }
}

// Get current data
$cities = $pdo->query("SELECT * FROM cities ORDER BY name")->fetchAll();
$services = $pdo->query("SELECT * FROM services ORDER BY name")->fetchAll();
$totalCombinations = $pdo->query("SELECT COUNT(*) as count FROM city_service")->fetch()['count'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cities & Services 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-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;
        }

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

        .form-card {
            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);
        }

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

        .form-icon {
            width: 50px;
            height: 50px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 1rem;
            font-size: 1.2rem;
            color: white;
        }

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

        .form-group {
            margin-bottom: 1.5rem;
        }

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

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

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

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

        .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-danger {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: white;
        }

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

        /* Data Grid */
        .data-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
        }

        .data-card {
            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);
        }

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

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

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

        .data-grid {
            display: grid;
            gap: 1rem;
            max-height: 400px;
            overflow-y: auto;
        }

        .data-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 1rem;
            background: #f8f9fa;
            border-radius: 12px;
            border: 1px solid #e9ecef;
            transition: all 0.3s ease;
        }

        .data-item:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }

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

        .item-info p {
            font-size: 0.8rem;
            color: #7f8c8d;
        }

        .item-actions {
            display: flex;
            gap: 0.5rem;
        }

        .btn-sm {
            padding: 0.5rem 1rem;
            font-size: 0.8rem;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .main-content {
                margin-left: 0;
                padding: 1rem;
            }
            
            .form-grid, .data-section {
                grid-template-columns: 1fr;
            }
        }

        /* 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; }
    </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="modern-content-management.php" class="nav-item">
                <i class="fas fa-edit"></i>
                <span>Content Management</span>
            </a>
            <a href="#" class="nav-item active">
                <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>Cities & Services Management 🏙️</h1>
            <p style="opacity: 0.9; font-size: 1.1rem;">Manage your website's cities and services efficiently</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"><?= count($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"><?= count($services) ?></div>
                <div class="stat-label">Total Services</div>
            </div>
            
            <div class="stat-card">
                <div class="stat-icon combinations">
                    <i class="fas fa-link"></i>
                </div>
                <div class="stat-value"><?= $totalCombinations ?></div>
                <div class="stat-label">Total Combinations</div>
            </div>
        </div>

        <!-- Forms -->
        <div class="form-grid animate-fade-in-up animate-delay-2">
            <!-- Add Single City -->
            <div class="form-card">
                <div class="form-header">
                    <div class="form-icon" style="background: linear-gradient(135deg, #667eea, #764ba2);">
                        <i class="fas fa-plus"></i>
                    </div>
                    <div class="form-title">Add New City</div>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="add_city">
                    <div class="form-group">
                        <label class="form-label">City Name</label>
                        <input type="text" name="city_name" class="form-input" 
                               placeholder="e.g., New Delhi, Mumbai, Bangalore" required>
                    </div>
                    <button type="submit" class="btn btn-primary" style="width: 100%;">
                        <i class="fas fa-plus"></i>Add City & Create Service Combinations
                    </button>
                </form>
            </div>

            <!-- Add Service -->
            <div class="form-card">
                <div class="form-header">
                    <div class="form-icon" style="background: linear-gradient(135deg, #f093fb, #f5576c);">
                        <i class="fas fa-cog"></i>
                    </div>
                    <div class="form-title">Add New Service</div>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="add_service">
                    <div class="form-group">
                        <label class="form-label">Service Name</label>
                        <input type="text" name="service_name" class="form-input" 
                               placeholder="e.g., Web Design, Digital Marketing" required>
                    </div>
                    <button type="submit" class="btn btn-success" style="width: 100%;">
                        <i class="fas fa-plus"></i>Add Service & Create City Combinations
                    </button>
                </form>
            </div>

            <!-- Bulk Add Cities -->
            <div class="form-card" style="grid-column: 1 / -1;">
                <div class="form-header">
                    <div class="form-icon" style="background: linear-gradient(135deg, #4facfe, #00f2fe);">
                        <i class="fas fa-layer-group"></i>
                    </div>
                    <div class="form-title">Bulk Add Cities</div>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="add_cities_bulk">
                    <div class="form-group">
                        <label class="form-label">City Names (separated by commas, semicolons, or new lines)</label>
                        <textarea name="cities_bulk" class="form-textarea" 
                                  placeholder="Mumbai, Delhi, Bangalore, Chennai, Kolkata, Hyderabad, Pune, Ahmedabad" required><?php echo isset($_POST['cities_bulk']) ? htmlspecialchars($_POST['cities_bulk']) : ''; ?></textarea>
                    </div>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-upload"></i>Bulk Add Cities & Create Service Combinations
                    </button>
                </form>
            </div>
        </div>

        <!-- Data Display -->
        <div class="data-section animate-fade-in-up animate-delay-3">
            <!-- Current Cities -->
            <div class="data-card">
                <div class="data-header">
                    <div class="data-title">
                        <i class="fas fa-city" style="margin-right: 0.5rem; color: #667eea;"></i>
                        Current Cities
                    </div>
                    <div class="data-count"><?= count($cities) ?></div>
                </div>
                <div class="data-grid">
                    <?php foreach ($cities as $city): ?>
                    <div class="data-item">
                        <div class="item-info">
                            <h4><?= htmlspecialchars($city['name']) ?></h4>
                            <p>Slug: <?= htmlspecialchars($city['slug']) ?></p>
                        </div>
                        <div class="item-actions">
                            <form method="POST" style="display: inline;" 
                                  onsubmit="return confirm('Are you sure? This will delete all service combinations for this city.')">
                                <input type="hidden" name="action" value="delete_city">
                                <input type="hidden" name="city_id" value="<?= $city['id'] ?>">
                                <button type="submit" class="btn btn-danger btn-sm">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Current Services -->
            <div class="data-card">
                <div class="data-header">
                    <div class="data-title">
                        <i class="fas fa-cogs" style="margin-right: 0.5rem; color: #f093fb;"></i>
                        Current Services
                    </div>
                    <div class="data-count"><?= count($services) ?></div>
                </div>
                <div class="data-grid">
                    <?php foreach ($services as $service): ?>
                    <div class="data-item">
                        <div class="item-info">
                            <h4><?= htmlspecialchars($service['name']) ?></h4>
                            <p>Slug: <?= htmlspecialchars($service['slug']) ?></p>
                        </div>
                        <div class="item-actions">
                            <form method="POST" style="display: inline;" 
                                  onsubmit="return confirm('Are you sure? This will delete all city combinations for this service.')">
                                <input type="hidden" name="action" value="delete_service">
                                <input type="hidden" name="service_id" value="<?= $service['id'] ?>">
                                <button type="submit" class="btn btn-danger btn-sm">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Add smooth animations on form submission
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function() {
                const button = this.querySelector('button[type="submit"]');
                if (button) {
                    const originalText = button.innerHTML;
                    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
                    button.disabled = true;
                    
                    // Re-enable after 10 seconds (fallback)
                    setTimeout(() => {
                        button.innerHTML = originalText;
                        button.disabled = false;
                    }, 10000);
                }
            });
        });

        // Add smooth scrolling
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                e.preventDefault();
                const target = document.querySelector(this.getAttribute('href'));
                if (target) {
                    target.scrollIntoView({
                        behavior: 'smooth'
                    });
                }
            });
        });
    </script>
</body>
</html>