<?php
// Simplified Cities & Services Management
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

// Centralized PDO connection
require_once __DIR__ . '/../includes/pdo.php';
$connection_type = 'PDO';

// Helper functions
function cityNameToSlug($name) {
    return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
}

function serviceNameToSlug($name) {
    return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add_city') {
        $cityName = trim($_POST['city_name'] ?? '');
        
        if (empty($cityName)) {
            $error_message = "City name is required.";
        } else {
            $citySlug = cityNameToSlug($cityName);
            
            try {
                if ($connection_type === 'PDO') {
                    // Check if city exists
                    $stmt = $pdo->prepare("SELECT id FROM cities WHERE slug = ?");
                    $stmt->execute([$citySlug]);
                    
                    if ($stmt->fetch()) {
                        $error_message = "City '$cityName' already exists.";
                    } else {
                        // Insert city
                        $stmt = $pdo->prepare("INSERT INTO cities (name, slug) VALUES (?, ?)");
                        $stmt->execute([$cityName, $citySlug]);
                        $cityId = $pdo->lastInsertId();
                        
                        // Get all services and create combinations
                        $servicesStmt = $pdo->query("SELECT id, name FROM services");
                        $services = $servicesStmt->fetchAll();
                        
                        $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.";
                            $content = "Looking for professional $serviceName services in $cityName? Contact Finggu Infotech for expert solutions.";
                            
                            $comboStmt = $pdo->prepare("INSERT INTO city_service (city_id, service_id, seo_title, seo_description, content) VALUES (?, ?, ?, ?, ?)");
                            $comboStmt->execute([$cityId, $service['id'], $seoTitle, $seoDescription, $content]);
                            $combinationsCreated++;
                        }
                        
                        $success_message = "City '$cityName' added successfully with $combinationsCreated service combinations!";
                    }
                } else {
                    // MySQLi version
                    $stmt = $conn->prepare("SELECT id FROM cities WHERE slug = ?");
                    $stmt->bind_param("s", $citySlug);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    
                    if ($result->fetch_assoc()) {
                        $error_message = "City '$cityName' already exists.";
                    } else {
                        $stmt = $conn->prepare("INSERT INTO cities (name, slug) VALUES (?, ?)");
                        $stmt->bind_param("ss", $cityName, $citySlug);
                        $stmt->execute();
                        $cityId = $conn->insert_id;
                        
                        // Get services
                        $servicesResult = $conn->query("SELECT id, name FROM services");
                        $combinationsCreated = 0;
                        
                        while ($service = $servicesResult->fetch_assoc()) {
                            $serviceName = $service['name'];
                            $seoTitle = "$serviceName in $cityName | Finggu Infotech";
                            $seoDescription = "Professional $serviceName services in $cityName. Get expert digital solutions from Finggu Infotech.";
                            $content = "Looking for professional $serviceName services in $cityName? Contact Finggu Infotech for expert solutions.";
                            
                            $comboStmt = $conn->prepare("INSERT INTO city_service (city_id, service_id, seo_title, seo_description, content) VALUES (?, ?, ?, ?, ?)");
                            $comboStmt->bind_param("iisss", $cityId, $service['id'], $seoTitle, $seoDescription, $content);
                            $comboStmt->execute();
                            $combinationsCreated++;
                        }
                        
                        $success_message = "City '$cityName' added successfully with $combinationsCreated service combinations!";
                    }
                }
            } catch (Exception $e) {
                $error_message = "Error adding city: " . $e->getMessage();
            }
        }
    }
    
    if ($action === 'add_service') {
        $serviceName = trim($_POST['service_name'] ?? '');
        
        if (empty($serviceName)) {
            $error_message = "Service name is required.";
        } else {
            $serviceSlug = serviceNameToSlug($serviceName);
            
            try {
                if ($connection_type === 'PDO') {
                    // Check if service exists
                    $stmt = $pdo->prepare("SELECT id FROM services WHERE slug = ?");
                    $stmt->execute([$serviceSlug]);
                    
                    if ($stmt->fetch()) {
                        $error_message = "Service '$serviceName' already exists.";
                    } else {
                        // Insert service
                        $stmt = $pdo->prepare("INSERT INTO services (name, slug) VALUES (?, ?)");
                        $stmt->execute([$serviceName, $serviceSlug]);
                        $serviceId = $pdo->lastInsertId();
                        
                        // Get all cities and create combinations
                        $citiesStmt = $pdo->query("SELECT id, name FROM cities");
                        $cities = $citiesStmt->fetchAll();
                        
                        $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.";
                            $content = "Looking for professional $serviceName services in $cityName? Contact Finggu Infotech for expert solutions.";
                            
                            $comboStmt = $pdo->prepare("INSERT INTO city_service (city_id, service_id, seo_title, seo_description, content) VALUES (?, ?, ?, ?, ?)");
                            $comboStmt->execute([$city['id'], $serviceId, $seoTitle, $seoDescription, $content]);
                            $combinationsCreated++;
                        }
                        
                        $success_message = "Service '$serviceName' added successfully with $combinationsCreated city combinations!";
                    }
                } else {
                    // MySQLi version
                    $stmt = $conn->prepare("SELECT id FROM services WHERE slug = ?");
                    $stmt->bind_param("s", $serviceSlug);
                    $stmt->execute();
                    $result = $stmt->get_result();
                    
                    if ($result->fetch_assoc()) {
                        $error_message = "Service '$serviceName' already exists.";
                    } else {
                        $stmt = $conn->prepare("INSERT INTO services (name, slug) VALUES (?, ?)");
                        $stmt->bind_param("ss", $serviceName, $serviceSlug);
                        $stmt->execute();
                        $serviceId = $conn->insert_id;
                        
                        // Get cities
                        $citiesResult = $conn->query("SELECT id, name FROM cities");
                        $combinationsCreated = 0;
                        
                        while ($city = $citiesResult->fetch_assoc()) {
                            $cityName = $city['name'];
                            $seoTitle = "$serviceName in $cityName | Finggu Infotech";
                            $seoDescription = "Professional $serviceName services in $cityName. Get expert digital solutions from Finggu Infotech.";
                            $content = "Looking for professional $serviceName services in $cityName? Contact Finggu Infotech for expert solutions.";
                            
                            $comboStmt = $conn->prepare("INSERT INTO city_service (city_id, service_id, seo_title, seo_description, content) VALUES (?, ?, ?, ?, ?)");
                            $comboStmt->bind_param("iisss", $city['id'], $serviceId, $seoTitle, $seoDescription, $content);
                            $comboStmt->execute();
                            $combinationsCreated++;
                        }
                        
                        $success_message = "Service '$serviceName' added successfully with $combinationsCreated city combinations!";
                    }
                }
            } catch (Exception $e) {
                $error_message = "Error adding service: " . $e->getMessage();
            }
        }
    }
}

// Get current data
try {
    if ($connection_type === 'PDO') {
        $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'];
    } else {
        $cities = [];
        $citiesResult = $conn->query("SELECT * FROM cities ORDER BY name");
        while ($row = $citiesResult->fetch_assoc()) {
            $cities[] = $row;
        }
        
        $services = [];
        $servicesResult = $conn->query("SELECT * FROM services ORDER BY name");
        while ($row = $servicesResult->fetch_assoc()) {
            $services[] = $row;
        }
        
        $countResult = $conn->query("SELECT COUNT(*) as count FROM city_service");
        $totalCombinations = $countResult->fetch_assoc()['count'];
    }
} catch (Exception $e) {
    $error_message = "Error loading data: " . $e->getMessage();
    $cities = [];
    $services = [];
    $totalCombinations = 0;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Cities & Services | Finggu Infotech Admin</title>
    <?php include 'includes/admin-styles.php'; ?>
</head>
<body>
    <div class="container mx-auto px-4 py-8">
        <?php include 'includes/admin-nav.php'; ?>

        <div class="mb-4 p-4 bg-blue-50 border border-blue-200 rounded">
            <p><strong>Connection:</strong> Using <?= $connection_type ?> | 
            <strong>Cities:</strong> <?= count($cities) ?> | 
            <strong>Services:</strong> <?= count($services) ?> | 
            <strong>Combinations:</strong> <?= $totalCombinations ?></p>
        </div>

        <!-- Messages -->
        <?php if ($success_message): ?>
            <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-6">
                <i class="fas fa-check-circle mr-2"></i><?= htmlspecialchars($success_message) ?>
            </div>
        <?php endif; ?>

        <?php if ($error_message): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                <i class="fas fa-exclamation-circle mr-2"></i><?= htmlspecialchars($error_message) ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- Add New City -->
            <div class="bg-white rounded-lg shadow-lg p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-4">
                    <i class="fas fa-plus-circle text-blue-600 mr-2"></i>Add New City
                </h2>
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="action" value="add_city">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">City Name</label>
                        <input type="text" name="city_name" required 
                               placeholder="e.g., New Delhi, Gurgaon, Noida" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    <button type="submit" 
                            class="w-full bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md transition-colors">
                        <i class="fas fa-plus mr-2"></i>Add City & Create Service Combinations
                    </button>
                </form>
            </div>

            <!-- Add New Service -->
            <div class="bg-white rounded-lg shadow-lg p-6">
                <h2 class="text-xl font-bold text-gray-800 mb-4">
                    <i class="fas fa-plus-circle text-green-600 mr-2"></i>Add New Service
                </h2>
                <form method="POST" class="space-y-4">
                    <input type="hidden" name="action" value="add_service">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Service Name</label>
                        <input type="text" name="service_name" required 
                               placeholder="e.g., Social Media Marketing, Content Writing" 
                               class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500">
                    </div>
                    <button type="submit" 
                            class="w-full bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md transition-colors">
                        <i class="fas fa-plus mr-2"></i>Add Service & Create City Combinations
                    </button>
                </form>
            </div>
        </div>

        <!-- Current Cities -->
        <div class="bg-white rounded-lg shadow-lg p-6 mt-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">
                <i class="fas fa-city text-blue-600 mr-2"></i>Current Cities (<?= count($cities) ?>)
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <?php foreach ($cities as $city): ?>
                <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                    <h3 class="font-medium text-gray-900"><?= htmlspecialchars($city['name']) ?></h3>
                    <p class="text-sm text-gray-500">Slug: <?= htmlspecialchars($city['slug']) ?></p>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Current Services -->
        <div class="bg-white rounded-lg shadow-lg p-6 mt-6">
            <h2 class="text-xl font-bold text-gray-800 mb-4">
                <i class="fas fa-cogs text-green-600 mr-2"></i>Current Services (<?= count($services) ?>)
            </h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <?php foreach ($services as $service): ?>
                <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
                    <h3 class="font-medium text-gray-900"><?= htmlspecialchars($service['name']) ?></h3>
                    <p class="text-sm text-gray-500">Slug: <?= htmlspecialchars($service['slug']) ?></p>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</body>
</html>