<?php
require_once 'auth.php';
require_once __DIR__ . '/../includes/db.php';

// List of Indian states with their common names and codes
$indianStates = [
    'Andhra Pradesh' => 'AP',
    'Arunachal Pradesh' => 'AR',
    'Assam' => 'AS',
    'Bihar' => 'BR',
    'Chhattisgarh' => 'CG',
    'Goa' => 'GA',
    'Gujarat' => 'GJ',
    'Haryana' => 'HR',
    'Himachal Pradesh' => 'HP',
    'Jharkhand' => 'JH',
    'Karnataka' => 'KA',
    'Kerala' => 'KL',
    'Madhya Pradesh' => 'MP',
    'Maharashtra' => 'MH',
    'Manipur' => 'MN',
    'Meghalaya' => 'ML',
    'Mizoram' => 'MZ',
    'Nagaland' => 'NL',
    'Odisha' => 'OD',
    'Punjab' => 'PB',
    'Rajasthan' => 'RJ',
    'Sikkim' => 'SK',
    'Tamil Nadu' => 'TN',
    'Telangana' => 'TS',
    'Tripura' => 'TR',
    'Uttar Pradesh' => 'UP',
    'Uttarakhand' => 'UK',
    'West Bengal' => 'WB',
    'Andaman and Nicobar Islands' => 'AN',
    'Chandigarh' => 'CH',
    'Dadra and Nagar Haveli and Daman and Diu' => 'DN',
    'Delhi' => 'DL',
    'Jammu and Kashmir' => 'JK',
    'Ladakh' => 'LA',
    'Lakshadweep' => 'LD',
    'Puducherry' => 'PY'
];

// Function to fetch cities by state from the API
function fetchCitiesByState($stateName, $stateCode) {
    $endpoints = [
        "https://raw.githubusercontent.com/dr5hn/countries-states-cities-database/master/countries+states+cities.json",
        "https://raw.githubusercontent.com/dr5hn/countries-states-cities-database/master/countries.json"
    ];
    
    // First try the direct state file
    $stateFile = "https://raw.githubusercontent.com/dr5hn/countries-states-cities-database/master/states/$stateCode.json";
    $json = @file_get_contents($stateFile, false, stream_context_create([
        'http' => ['ignore_errors' => true],
        'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]
    ]));
    
    if ($json !== false) {
        $data = json_decode($json, true);
        if (json_last_error() === JSON_ERROR_NONE && !empty($data['cities'])) {
            return $data['cities'];
        }
    }
    
    foreach ($endpoints as $apiUrl) {
        try {
            $json = @file_get_contents($apiUrl, false, stream_context_create([
                'http' => ['ignore_errors' => true],
                'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]
            ]));
            
            if ($json === false) continue;
            
            $data = json_decode($json, true);
            if (json_last_error() !== JSON_ERROR_NONE) continue;
            
            // Find India in the data
            foreach ($data as $country) {
                if (strtolower($country['name']) === 'india' || $country['iso2'] === 'IN') {
                    // Find the state
                    foreach ($country['states'] ?? [] as $state) {
                        if (strtolower($state['name']) === strtolower($stateName) || 
                            strtoupper($state['state_code']) === strtoupper($stateCode)) {
                            return $state['cities'] ?? [];
                        }
                    }
                }
            }
        } catch (Exception $e) {
            error_log("Error fetching from $apiUrl: " . $e->getMessage());
            continue;
        }
    }
    
    // If API fails, try local fallback
    $localFile = __DIR__ . "/data/" . strtolower(str_replace(' ', '-', $stateName)) . "-cities.json";
    if (file_exists($localFile)) {
        $cities = json_decode(file_get_contents($localFile), true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return $cities;
        }
    }
    
    return [];
}

// Handle form submission
$exported = false;
$error = '';
$stateName = $_GET['state'] ?? 'Maharashtra';
$stateCode = $_GET['state_code'] ?? ($indianStates[$stateName] ?? 'MH');

if (isset($_GET['export']) && $stateName) {
    $cities = fetchCitiesByState($stateName, $stateCode);
    
    if (!empty($cities)) {
        $exportData = [
            'state' => $stateName,
            'state_code' => $stateCode,
            'country' => 'India',
            'country_code' => 'IN',
            'total_cities' => count($cities),
            'exported_at' => date('Y-m-d H:i:s'),
            'cities' => array_map(function($city) use ($stateName, $stateCode) {
                return [
                    'name' => $city['name'],
                    'state' => $stateName,
                    'state_code' => $stateCode,
                    'country' => 'India',
                    'country_code' => 'IN',
                    'latitude' => $city['latitude'] ?? null,
                    'longitude' => $city['longitude'] ?? null
                ];
            }, $cities)
        ];
        
        // Set headers for download
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename="' . 
               strtolower(str_replace(' ', '_', $stateName)) . '_cities_' . date('Y-m-d') . '.json"');
        
        echo json_encode($exportData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    } else {
        $error = "No cities found for $stateName. Please try another state or check your internet connection.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Export Indian Cities by State</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
</head>
<body class="bg-gray-100 p-8">
    <div class="max-w-4xl mx-auto bg-white rounded-lg shadow-md p-6">
        <h1 class="text-2xl font-bold text-gray-800 mb-6">Export Indian Cities by State</h1>
        
        <?php if ($error): ?>
            <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>
        
        <form method="GET" class="space-y-4">
            <div>
                <label for="state" class="block text-sm font-medium text-gray-700 mb-1">Select State:</label>
                <select name="state" id="state" class="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500">
                    <?php foreach ($indianStates as $name => $code): ?>
                        <option value="<?php echo htmlspecialchars($name); ?>" 
                                data-code="<?php echo htmlspecialchars($code); ?>"
                                <?php echo ($name === $stateName) ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($name); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <input type="hidden" name="state_code" id="state_code" value="<?php echo htmlspecialchars($stateCode); ?>">
            </div>
            
            <div class="pt-4">
                <button type="submit" name="export" value="1" 
                        class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                    <svg class="-ml-1 mr-2 h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clip-rule="evenodd" />
                    </svg>
                    Export Cities
                </button>
            </div>
        </form>
        
        <?php if (isset($exportData) && !empty($exportData['cities'])): ?>
        <div class="mt-8">
            <h2 class="text-lg font-medium text-gray-900 mb-4">Preview (first 10 cities)</h2>
            <div class="bg-gray-50 p-4 rounded-lg max-h-60 overflow-y-auto">
                <pre class="text-xs text-gray-600"><?php 
                    $preview = $exportData;
                    $preview['cities'] = array_slice($preview['cities'], 0, 10);
                    echo htmlspecialchars(json_encode($preview, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); 
                ?></pre>
            </div>
            <p class="mt-2 text-sm text-gray-500">
                Total cities: <?php echo count($exportData['cities']); ?> 
                (showing first 10 in preview)
            </p>
        </div>
        <?php endif; ?>
    </div>
    
    <script>
        // Update state code when state selection changes
        document.getElementById('state').addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            document.getElementById('state_code').value = selectedOption.dataset.code;
        });
    </script>
</body>
</html>
