<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit();
}

$pdo = getDBConnection();
$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'export_json':
                try {
                    $stmt = $pdo->prepare("
                        SELECT date, tithi, nakshatra, yoga, karana, muhurat, rahu_kaal, gulika_kaal, 
                               sunrise, sunset, moonrise, moonset, special_day, festival, remarks, 
                               created_at, updated_at
                        FROM panchang_data 
                        ORDER BY date ASC
                    ");
                    $stmt->execute();
                    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    header('Content-Type: application/json');
                    header('Content-Disposition: attachment; filename="panchang_data_' . date('Y-m-d_H-i-s') . '.json"');
                    echo json_encode($data, JSON_PRETTY_PRINT);
                    exit();
                } catch (Exception $e) {
                    $error = 'Error exporting JSON: ' . $e->getMessage();
                }
                break;
                
            case 'export_csv':
                try {
                    $stmt = $pdo->prepare("
                        SELECT date, tithi, nakshatra, yoga, karana, muhurat, rahu_kaal, gulika_kaal, 
                               sunrise, sunset, moonrise, moonset, special_day, festival, remarks, 
                               created_at, updated_at
                        FROM panchang_data 
                        ORDER BY date ASC
                    ");
                    $stmt->execute();
                    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    header('Content-Type: text/csv');
                    header('Content-Disposition: attachment; filename="panchang_data_' . date('Y-m-d_H-i-s') . '.csv"');
                    
                    $output = fopen('php://output', 'w');
                    
                    if (!empty($data)) {
                        fputcsv($output, array_keys($data[0]));
                        foreach ($data as $row) {
                            fputcsv($output, $row);
                        }
                    }
                    
                    fclose($output);
                    exit();
                } catch (Exception $e) {
                    $error = 'Error exporting CSV: ' . $e->getMessage();
                }
                break;
                
            case 'import_json':
                try {
                    $jsonData = $_POST['json_data'];
                    $clearExisting = isset($_POST['clear_existing']);
                    
                    if (empty($jsonData)) {
                        throw new Exception('Please paste JSON data');
                    }
                    
                    $data = json_decode($jsonData, true);
                    
                    if (json_last_error() !== JSON_ERROR_NONE) {
                        throw new Exception('Invalid JSON format: ' . json_last_error_msg());
                    }
                    
                    if (!$data || !is_array($data)) {
                        throw new Exception('JSON data must be an array of objects');
                    }
                    
                    $pdo->beginTransaction();
                    
                    if ($clearExisting) {
                        $clearStmt = $pdo->prepare("DELETE FROM panchang_data");
                        $clearStmt->execute();
                    }
                    
                    $insertStmt = $pdo->prepare("
                        INSERT INTO panchang_data (date, tithi, nakshatra, yoga, karana, muhurat, rahu_kaal, gulika_kaal, 
                                                 sunrise, sunset, moonrise, moonset, special_day, festival, remarks, created_at, updated_at)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
                    ");
                    
                    $inserted = 0;
                    foreach ($data as $row) {
                        $insertStmt->execute([
                            $row['date'] ?? '',
                            $row['tithi'] ?? '',
                            $row['nakshatra'] ?? '',
                            $row['yoga'] ?? '',
                            $row['karana'] ?? '',
                            $row['muhurat'] ?? '',
                            $row['rahu_kaal'] ?? '',
                            $row['gulika_kaal'] ?? '',
                            $row['sunrise'] ?? '',
                            $row['sunset'] ?? '',
                            $row['moonrise'] ?? '',
                            $row['moonset'] ?? '',
                            $row['special_day'] ?? '',
                            $row['festival'] ?? '',
                            $row['remarks'] ?? ''
                        ]);
                        $inserted++;
                    }
                    
                    $pdo->commit();
                    $message = "✅ Successfully imported $inserted entries from JSON data!";
                    
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $error = 'Error importing JSON: ' . $e->getMessage();
                }
                break;
        }
    }
}

// Get current data count
$countStmt = $pdo->prepare("SELECT COUNT(*) as count FROM panchang_data");
$countStmt->execute();
$dataCount = $countStmt->fetch(PDO::FETCH_ASSOC)['count'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panchang Export/Import - Astro Admin</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .header h1 {
            margin: 0;
            font-size: 2.5em;
        }
        
        .content {
            padding: 30px;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }
        
        .stat-card h3 {
            margin: 0 0 10px 0;
            font-size: 2em;
        }
        
        .stat-card p {
            margin: 0;
            opacity: 0.9;
        }
        
        .section {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 10px;
            margin-bottom: 25px;
            border-left: 5px solid #667eea;
        }
        
        .section h2 {
            margin-top: 0;
            color: #333;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }
        
        .form-group input, .form-group textarea, .form-group select {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            transition: border-color 0.3s;
        }
        
        .form-group input:focus, .form-group textarea:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .form-group textarea {
            height: 200px;
            resize: vertical;
            font-family: monospace;
        }
        
        .checkbox-group {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: transform 0.2s;
            text-decoration: none;
            display: inline-block;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        
        .btn:hover {
            transform: translateY(-2px);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        .alert {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .export-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 30px;
        }
        
        .json-preview {
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-top: 10px;
            max-height: 300px;
            overflow-y: auto;
        }
        
        .json-preview pre {
            margin: 0;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔮 Panchang Export/Import</h1>
            <p>Manage your panchang data with ease</p>
        </div>
        
        <div class="content">
            <?php if ($message): ?>
                <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>
            
            <!-- Statistics -->
            <div class="stats">
                <div class="stat-card">
                    <h3><?php echo $dataCount; ?></h3>
                    <p>Total Panchang Entries</p>
                </div>
                <div class="stat-card">
                    <h3><?php echo date('Y-m-d'); ?></h3>
                    <p>Last Updated</p>
                </div>
            </div>
            
            <!-- Export Section -->
            <div class="section">
                <h2>📤 Export Data</h2>
                <p>Download your panchang data in various formats</p>
                
                <div class="export-buttons">
                    <form method="POST" style="display: inline;">
                        <input type="hidden" name="action" value="export_json">
                        <button type="submit" class="btn btn-success">
                            📄 Export JSON
                        </button>
                    </form>
                    
                    <form method="POST" style="display: inline;">
                        <input type="hidden" name="action" value="export_csv">
                        <button type="submit" class="btn btn-success">
                            📊 Export CSV
                        </button>
                    </form>
                </div>
            </div>
            
            <!-- Import Section -->
            <div class="section">
                <h2>📥 Import Data</h2>
                <p>Import panchang data from JSON format</p>
                
                <form method="POST">
                    <input type="hidden" name="action" value="import_json">
                    
                    <div class="form-group">
                        <label for="json_data">JSON Data:</label>
                        <textarea 
                            id="json_data" 
                            name="json_data" 
                            placeholder="Paste your JSON data here..."
                            required
                        ></textarea>
                    </div>
                    
                    <div class="form-group">
                        <div class="checkbox-group">
                            <input type="checkbox" id="clear_existing" name="clear_existing">
                            <label for="clear_existing">Clear existing data before import</label>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-danger">
                        📥 Import JSON Data
                    </button>
                </form>
            </div>
            
            <!-- Sample JSON -->
            <div class="section">
                <h2>📋 Sample JSON Format</h2>
                <p>Use this format for importing data:</p>
                <div class="json-preview">
                    <pre>[
  {
    "date": "2024-01-01",
    "tithi": "Purnima",
    "nakshatra": "Rohini",
    "yoga": "Siddhi",
    "karana": "Vishti",
    "muhurat": "06:00-08:00",
    "rahu_kaal": "07:30-09:00",
    "gulika_kaal": "12:00-13:30",
    "sunrise": "07:00",
    "sunset": "18:00",
    "moonrise": "19:00",
    "moonset": "07:30",
    "special_day": "New Year",
    "festival": "New Year Celebration",
    "remarks": "Auspicious day"
  }
]</pre>
                </div>
            </div>
            
            <!-- Navigation -->
            <div style="text-align: center; margin-top: 30px;">
                <a href="panchang_management.php" class="btn">← Back to Panchang Management</a>
                <a href="dashboard.php" class="btn">🏠 Dashboard</a>
            </div>
        </div>
    </div>
    
    <script>
        // JSON Import Form Validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const jsonData = document.getElementById('json_data').value.trim();
            
            if (!jsonData) {
                e.preventDefault();
                alert('Please paste JSON data');
                return;
            }
            
            // Validate JSON format
            try {
                const parsedData = JSON.parse(jsonData);
                if (!Array.isArray(parsedData)) {
                    e.preventDefault();
                    alert('JSON data must be an array of objects');
                    return;
                }
                
                if (parsedData.length === 0) {
                    e.preventDefault();
                    alert('JSON data cannot be empty');
                    return;
                }
                
                // Show loading
                const submitBtn = this.querySelector('button[type="submit"]');
                const originalText = submitBtn.innerHTML;
                submitBtn.innerHTML = '⏳ Importing...';
                submitBtn.disabled = true;
                
            } catch (error) {
                e.preventDefault();
                alert('Invalid JSON format: ' + error.message);
                return;
            }
        });
    </script>
</body>
</html>
