<?php
require_once 'auth.php';

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

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

$success_message = '';
$error_message = '';
$sync_results = [];

// Handle sync operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        $pdo->beginTransaction();
        
        if ($action === 'sync_missing') {
            // Find missing combinations
            $stmt = $pdo->query("
                SELECT c.id as city_id, c.name as city_name, s.id as service_id, s.name as service_name
                FROM cities c
                CROSS JOIN services s
                LEFT JOIN city_service cs ON c.id = cs.city_id AND s.id = cs.service_id
                WHERE cs.id IS NULL
            ");
            $missing = $stmt->fetchAll();
            
            if (empty($missing)) {
                $success_message = "✅ All city-service combinations already exist! No sync needed.";
            } else {
                $insertStmt = $pdo->prepare("
                    INSERT INTO city_service (city_id, service_id, seo_title, seo_description, content)
                    VALUES (?, ?, ?, ?, ?)
                ");
                
                $created = 0;
                foreach ($missing as $combo) {
                    $cityName = $combo['city_name'];
                    $serviceName = $combo['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.";
                    
                    $insertStmt->execute([$combo['city_id'], $combo['service_id'], $seoTitle, $seoDescription, $content]);
                    $created++;
                }
                
                $success_message = "✅ Successfully created $created missing city-service combinations!";
                $sync_results['created'] = $created;
            }
        }
        
        elseif ($action === 'update_timestamps') {
            $stmt = $pdo->query("UPDATE city_service SET updated_at = NOW()");
            $updated = $stmt->rowCount();
            $success_message = "✅ Updated timestamps for $updated records!";
            $sync_results['updated'] = $updated;
        }
        
        elseif ($action === 'cleanup_orphans') {
            // Remove city_service records where city or service no longer exists
            $stmt = $pdo->query("
                DELETE cs FROM city_service cs
                LEFT JOIN cities c ON cs.city_id = c.id
                LEFT JOIN services s ON cs.service_id = s.id
                WHERE c.id IS NULL OR s.id IS NULL
            ");
            $cleaned = $stmt->rowCount();
            $success_message = "✅ Cleaned up $cleaned orphaned records!";
            $sync_results['cleaned'] = $cleaned;
        }
        
        elseif ($action === 'full_sync') {
            // Complete synchronization
            $operations = [];
            
            // 1. Create missing combinations
            $stmt = $pdo->query("
                SELECT c.id as city_id, c.name as city_name, s.id as service_id, s.name as service_name
                FROM cities c
                CROSS JOIN services s
                LEFT JOIN city_service cs ON c.id = cs.city_id AND s.id = cs.service_id
                WHERE cs.id IS NULL
            ");
            $missing = $stmt->fetchAll();
            
            if (!empty($missing)) {
                $insertStmt = $pdo->prepare("
                    INSERT INTO city_service (city_id, service_id, seo_title, seo_description, content)
                    VALUES (?, ?, ?, ?, ?)
                ");
                
                foreach ($missing as $combo) {
                    $cityName = $combo['city_name'];
                    $serviceName = $combo['service_name'];
                    
                    $seoTitle = "$serviceName in $cityName | Finggu Infotech";
                    $seoDescription = "Professional $serviceName services in $cityName. Get expert digital solutions from Finggu Infotech.";
                    $content = "Professional $serviceName services in $cityName. Contact Finggu Infotech for expert solutions.";
                    
                    $insertStmt->execute([$combo['city_id'], $combo['service_id'], $seoTitle, $seoDescription, $content]);
                }
                $operations[] = "Created " . count($missing) . " missing combinations";
                $sync_results['created'] = count($missing);
            }
            
            // 2. Clean up orphans
            $stmt = $pdo->query("
                DELETE cs FROM city_service cs
                LEFT JOIN cities c ON cs.city_id = c.id
                LEFT JOIN services s ON cs.service_id = s.id
                WHERE c.id IS NULL OR s.id IS NULL
            ");
            $cleaned = $stmt->rowCount();
            if ($cleaned > 0) {
                $operations[] = "Cleaned $cleaned orphaned records";
                $sync_results['cleaned'] = $cleaned;
            }
            
            // 3. Update timestamps
            $stmt = $pdo->query("UPDATE city_service SET updated_at = NOW() WHERE updated_at < DATE_SUB(NOW(), INTERVAL 1 DAY)");
            $updated = $stmt->rowCount();
            if ($updated > 0) {
                $operations[] = "Updated $updated timestamps";
                $sync_results['updated'] = $updated;
            }
            
            $success_message = "✅ Full sync completed! " . implode(', ', $operations);
        }
        
        $pdo->commit();
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_message = "Error during sync: " . $e->getMessage();
    }
}

// Get current 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(),
    'expected_combinations' => 0,
    'missing_combinations' => 0,
    'orphaned_records' => 0,
    'last_updated' => $pdo->query("SELECT MAX(updated_at) FROM city_service")->fetchColumn()
];

$stats['expected_combinations'] = $stats['total_cities'] * $stats['total_services'];
$stats['missing_combinations'] = $pdo->query("
    SELECT COUNT(*)
    FROM cities c
    CROSS JOIN services s
    LEFT JOIN city_service cs ON c.id = cs.city_id AND s.id = cs.service_id
    WHERE cs.id IS NULL
")->fetchColumn();

$stats['orphaned_records'] = $pdo->query("
    SELECT COUNT(*)
    FROM city_service cs
    LEFT JOIN cities c ON cs.city_id = c.id
    LEFT JOIN services s ON cs.service_id = s.id
    WHERE c.id IS NULL OR s.id IS NULL
")->fetchColumn();

$sync_health = $stats['expected_combinations'] > 0 ? 
    round(($stats['total_combinations'] / $stats['expected_combinations']) * 100) : 100;

// Get recent sync activity
$recentActivity = $pdo->query("
    SELECT cs.updated_at, c.name as city_name, s.name as service_name
    FROM city_service cs
    JOIN cities c ON cs.city_id = c.id
    JOIN services s ON cs.service_id = s.id
    ORDER BY cs.updated_at DESC
    LIMIT 10
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Synchronization | 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;
        }

        /* Health Status */
        .health-status {
            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);
            text-align: center;
        }

        .health-circle {
            position: relative;
            width: 150px;
            height: 150px;
            margin: 0 auto 1rem;
        }

        .health-circle svg {
            width: 100%;
            height: 100%;
            transform: rotate(-90deg);
        }

        .health-circle .bg {
            fill: none;
            stroke: #e9ecef;
            stroke-width: 12;
        }

        .health-circle .progress {
            fill: none;
            stroke: url(https://www.finggu.com/#healthGradient);
            stroke-width: 12;
            stroke-linecap: round;
            transition: stroke-dasharray 2s ease;
        }

        .health-text {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }

        .health-percentage {
            font-size: 2rem;
            font-weight: 800;
            color: #2c3e50;
        }

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

        .health-title {
            font-size: 1.5rem;
            font-weight: 700;
            color: #2c3e50;
            margin-bottom: 0.5rem;
        }

        .health-description {
            color: #7f8c8d;
            margin-bottom: 1rem;
        }

        /* Stats Grid */
        .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;
            position: relative;
            overflow: hidden;
        }

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

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--gradient);
        }

        .stat-card.cities::before { --gradient: linear-gradient(135deg, #667eea, #764ba2); }
        .stat-card.services::before { --gradient: linear-gradient(135deg, #f093fb, #f5576c); }
        .stat-card.combinations::before { --gradient: linear-gradient(135deg, #4facfe, #00f2fe); }
        .stat-card.missing::before { --gradient: linear-gradient(135deg, #e74c3c, #c0392b); }

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

        .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;
        }

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

        .action-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);
            transition: all 0.3s ease;
        }

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

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

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

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

        .action-description {
            color: #7f8c8d;
            margin-bottom: 1.5rem;
            line-height: 1.6;
        }

        .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-success {
            background: linear-gradient(135deg, #2ecc71, #27ae60);
            color: white;
        }

        .btn-warning {
            background: linear-gradient(135deg, #f39c12, #e67e22);
            color: white;
        }

        .btn-danger {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
            color: white;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
        }

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

        /* Activity Section */
        .activity-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);
        }

        .activity-header {
            display: flex;
            align-items: center;
            margin-bottom: 2rem;
        }

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

        .activity-item {
            display: flex;
            align-items: center;
            padding: 1rem 0;
            border-bottom: 1px solid #e9ecef;
        }

        .activity-item:last-child {
            border-bottom: none;
        }

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

        .activity-content {
            flex: 1;
        }

        .activity-text {
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 0.25rem;
        }

        .activity-time {
            font-size: 0.8rem;
            color: #7f8c8d;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
            }
            
            .main-content {
                margin-left: 0;
                padding: 1rem;
            }
            
            .action-grid {
                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; }

        /* Pulse animation for sync status */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.7; }
        }

        .pulse {
            animation: pulse 2s infinite;
        }
    </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="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="#" class="nav-item active">
                <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>Data Synchronization ⚡</h1>
            <p style="opacity: 0.9; font-size: 1.1rem;">Keep your website data synchronized and optimized</p>
        </div>

        <!-- Messages -->
        <?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; ?>

        <!-- Sync Health Status -->
        <div class="health-status animate-fade-in-up animate-delay-1">
            <div class="health-circle">
                <svg>
                    <defs>
                        <linearGradient id="healthGradient" x1="0%" y1="0%" x2="100%" y2="0%">
                            <stop offset="0%" style="stop-color:<?= $sync_health >= 90 ? '#2ecc71' : ($sync_health >= 70 ? '#f39c12' : '#e74c3c') ?>"/>
                            <stop offset="100%" style="stop-color:<?= $sync_health >= 90 ? '#27ae60' : ($sync_health >= 70 ? '#e67e22' : '#c0392b') ?>"/>
                        </linearGradient>
                    </defs>
                    <circle class="bg" cx="75" cy="75" r="65"/>
                    <circle class="progress" cx="75" cy="75" r="65" 
                            stroke-dasharray="<?= $sync_health * 4.08 ?> 408" 
                            stroke-dashoffset="0"/>
                </svg>
                <div class="health-text">
                    <div class="health-percentage"><?= $sync_health ?>%</div>
                    <div class="health-label">Sync Health</div>
                </div>
            </div>
            <div class="health-title">
                <?php if ($sync_health >= 90): ?>
                    Excellent Sync Status
                <?php elseif ($sync_health >= 70): ?>
                    Good Sync Status
                <?php else: ?>
                    Needs Attention
                <?php endif; ?>
            </div>
            <div class="health-description">
                Your data synchronization is <?= $sync_health >= 90 ? 'running perfectly' : ($sync_health >= 70 ? 'working well' : 'requiring maintenance') ?>.
                <?php if ($stats['missing_combinations'] > 0): ?>
                    There are <?= $stats['missing_combinations'] ?> missing combinations that need to be created.
                <?php endif; ?>
            </div>
        </div>

        <!-- Statistics -->
        <div class="stats-grid animate-fade-in-up animate-delay-2">
            <div class="stat-card cities">
                <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 services">
                <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 combinations">
                <div class="stat-icon combinations">
                    <i class="fas fa-link"></i>
                </div>
                <div class="stat-value"><?= $stats['total_combinations'] ?></div>
                <div class="stat-label">Current Combinations</div>
            </div>
            
            <div class="stat-card missing">
                <div class="stat-icon missing">
                    <i class="fas fa-exclamation-triangle"></i>
                </div>
                <div class="stat-value <?= $stats['missing_combinations'] > 0 ? 'pulse' : '' ?>"><?= $stats['missing_combinations'] ?></div>
                <div class="stat-label">Missing Combinations</div>
            </div>
        </div>

        <!-- Sync Actions -->
        <div class="action-grid animate-fade-in-up animate-delay-3">
            <div class="action-card">
                <div class="action-header">
                    <div class="action-icon" style="background: linear-gradient(135deg, #2ecc71, #27ae60);">
                        <i class="fas fa-plus-circle"></i>
                    </div>
                    <div class="action-title">Create Missing Combinations</div>
                </div>
                <div class="action-description">
                    Generate all missing city-service combinations. This ensures every city has a page for every service you offer.
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="sync_missing">
                    <button type="submit" class="btn btn-success" style="width: 100%;" 
                            <?= $stats['missing_combinations'] == 0 ? 'disabled' : '' ?>>
                        <i class="fas fa-plus-circle"></i>
                        <?= $stats['missing_combinations'] > 0 ? "Create {$stats['missing_combinations']} Missing" : "All Combinations Exist" ?>
                    </button>
                </form>
            </div>

            <div class="action-card">
                <div class="action-header">
                    <div class="action-icon" style="background: linear-gradient(135deg, #f39c12, #e67e22);">
                        <i class="fas fa-clock"></i>
                    </div>
                    <div class="action-title">Update Timestamps</div>
                </div>
                <div class="action-description">
                    Refresh the last updated timestamps for all records. This helps with SEO and content freshness signals.
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="update_timestamps">
                    <button type="submit" class="btn btn-warning" style="width: 100%;">
                        <i class="fas fa-clock"></i>Update All Timestamps
                    </button>
                </form>
            </div>

            <div class="action-card">
                <div class="action-header">
                    <div class="action-icon" style="background: linear-gradient(135deg, #e74c3c, #c0392b);">
                        <i class="fas fa-trash-alt"></i>
                    </div>
                    <div class="action-title">Clean Orphaned Records</div>
                </div>
                <div class="action-description">
                    Remove city-service combinations that reference deleted cities or services. Keeps your database clean.
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="cleanup_orphans">
                    <button type="submit" class="btn btn-danger" style="width: 100%;" 
                            <?= $stats['orphaned_records'] == 0 ? 'disabled' : '' ?>>
                        <i class="fas fa-trash-alt"></i>
                        <?= $stats['orphaned_records'] > 0 ? "Clean {$stats['orphaned_records']} Orphaned" : "No Orphaned Records" ?>
                    </button>
                </form>
            </div>

            <div class="action-card">
                <div class="action-header">
                    <div class="action-icon" style="background: linear-gradient(135deg, #667eea, #764ba2);">
                        <i class="fas fa-sync-alt"></i>
                    </div>
                    <div class="action-title">Full Synchronization</div>
                </div>
                <div class="action-description">
                    Perform a complete sync operation: create missing combinations, clean orphans, and update timestamps.
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="full_sync">
                    <button type="submit" class="btn btn-primary" style="width: 100%;">
                        <i class="fas fa-sync-alt"></i>Run Full Sync
                    </button>
                </form>
            </div>
        </div>

        <!-- Recent Activity -->
        <?php if (!empty($recentActivity)): ?>
        <div class="activity-section animate-fade-in-up animate-delay-3">
            <div class="activity-header">
                <div class="activity-title">
                    <i class="fas fa-history" style="margin-right: 0.5rem; color: #667eea;"></i>
                    Recent Sync Activity
                </div>
            </div>
            
            <?php foreach (array_slice($recentActivity, 0, 8) as $activity): ?>
            <div class="activity-item">
                <div class="activity-icon">
                    <i class="fas fa-sync"></i>
                </div>
                <div class="activity-content">
                    <div class="activity-text">
                        <?= htmlspecialchars($activity['service_name']) ?> in <?= htmlspecialchars($activity['city_name']) ?>
                    </div>
                    <div class="activity-time">
                        Updated <?= date('M j, Y g:i A', strtotime($activity['updated_at'])) ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>
    </div>

    <script>
        // Add loading states to buttons
        document.querySelectorAll('form').forEach(form => {
            form.addEventListener('submit', function() {
                const button = this.querySelector('button[type="submit"]');
                if (button && !button.disabled) {
                    const originalText = button.innerHTML;
                    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
                    button.disabled = true;
                    
                    // Re-enable after 30 seconds (fallback)
                    setTimeout(() => {
                        button.innerHTML = originalText;
                        button.disabled = false;
                    }, 30000);
                }
            });
        });

        // Animate health circle on load
        setTimeout(() => {
            const healthCircle = document.querySelector('.health-circle .progress');
            if (healthCircle) {
                const percentage = <?= $sync_health ?>;
                const circumference = 2 * Math.PI * 65;
                const offset = circumference - (percentage / 100) * circumference;
                healthCircle.style.strokeDasharray = `${circumference} ${circumference}`;
                healthCircle.style.strokeDashoffset = offset;
            }
        }, 500);

        // Auto-refresh sync status every 30 seconds
        setInterval(() => {
            // Could implement auto-refresh here
            console.log('Sync status check...');
        }, 30000);
    </script>
</body>
</html>