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

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

$pdo = getDBConnection();

// Handle CSV upload
$upload_message = '';
$upload_status = '';

if ($_POST && isset($_FILES['csv_file'])) {
    $file = $_FILES['csv_file'];
    if ($file['error'] === UPLOAD_ERR_OK) {
        $csv_content = file_get_contents($file['tmp_name']);
        
        // Call API to upload CSV
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://astro.siddharthnahar.in/astro_admin/api/panchang_management.php?action=upload-csv');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $csv_content);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: text/csv',
            'Authorization: Bearer admin_token'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($http_code === 200) {
            $result = json_decode($response, true);
            if ($result['success']) {
                $upload_message = $result['message'];
                $upload_status = 'success';
            } else {
                $upload_message = $result['message'];
                $upload_status = 'error';
            }
        } else {
            $upload_message = 'Upload failed. HTTP Code: ' . $http_code;
            $upload_status = 'error';
        }
    } else {
        $upload_message = 'File upload error: ' . $file['error'];
        $upload_status = 'error';
    }
}

// Get Panchang data
$panchang_data = [];
try {
    $stmt = $pdo->query("SELECT * FROM panchang_data ORDER BY date ASC");
    $panchang_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Table might not exist yet
    $panchang_data = [];
}

// Get statistics
$stats = [];
try {
    $stmt = $pdo->query("SELECT COUNT(*) as total FROM panchang_data");
    $stats['total'] = $stmt->fetchColumn();
    
    $stmt = $pdo->query("SELECT COUNT(*) as with_tithi FROM panchang_data WHERE tithi IS NOT NULL AND tithi != ''");
    $stats['with_tithi'] = $stmt->fetchColumn();
    
    $stmt = $pdo->query("SELECT COUNT(*) as festivals FROM panchang_data WHERE festival IS NOT NULL AND festival != ''");
    $stats['festivals'] = $stmt->fetchColumn();
    
    $stmt = $pdo->query("SELECT MIN(date) as earliest, MAX(date) as latest FROM panchang_data");
    $date_range = $stmt->fetch(PDO::FETCH_ASSOC);
    $stats['earliest'] = $date_range['earliest'] ?? 'N/A';
    $stats['latest'] = $date_range['latest'] ?? 'N/A';
} catch (Exception $e) {
    $stats = ['total' => 0, 'with_tithi' => 0, 'festivals' => 0, 'earliest' => 'N/A', 'latest' => 'N/A'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panchang Management - Astro Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap5.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: 100vh;
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
        }
        .sidebar .nav-link {
            color: #fff;
            padding: 12px 20px;
            margin: 5px 0;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.1);
            transform: translateX(5px);
        }
        .main-content {
            background: #f8f9fa;
            min-height: 100vh;
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        .upload-area {
            border: 2px dashed #dee2e6;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s;
        }
        .upload-area:hover {
            border-color: #007bff;
            background: #f8f9fa;
        }
        .table-responsive {
            border-radius: 10px;
            overflow: hidden;
        }
        .btn-action {
            padding: 5px 10px;
            margin: 2px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar">
                    <div class="p-3">
                        <h4 class="text-white mb-4">
                            <i class="fas fa-star"></i> Astro Admin
                        </h4>
                        <nav class="nav flex-column">
                            <a class="nav-link" href="index.php">
                                <i class="fas fa-tachometer-alt"></i> Dashboard
                            </a>
                            <a class="nav-link" href="appointments.php">
                                <i class="fas fa-calendar-check"></i> Appointments
                            </a>
                            <a class="nav-link" href="users.php">
                                <i class="fas fa-users"></i> Users
                            </a>
                            <a class="nav-link" href="notifications.php">
                                <i class="fas fa-bell"></i> Notifications
                            </a>
                            <a class="nav-link active" href="panchang_management.php">
                                <i class="fas fa-calendar-alt"></i> Panchang Management
                            </a>
                            <a class="nav-link" href="wallet_management.php">
                                <i class="fas fa-wallet"></i> Wallet Management
                            </a>
                            <a class="nav-link" href="settings.php">
                                <i class="fas fa-cog"></i> Settings
                            </a>
                            <a class="nav-link" href="logout.php">
                                <i class="fas fa-sign-out-alt"></i> Logout
                            </a>
                        </nav>
                    </div>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10 main-content">
                <div class="p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h2><i class="fas fa-calendar-alt"></i> Panchang Management</h2>
                        <button class="btn btn-primary" onclick="showAddEntryModal()">
                            <i class="fas fa-plus"></i> Add Entry
                        </button>
                    </div>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-md-3">
                            <div class="card stats-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-calendar fa-2x mb-2"></i>
                                    <h4><?php echo $stats['total']; ?></h4>
                                    <p class="mb-0">Total Entries</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card stats-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-sun fa-2x mb-2"></i>
                                    <h4><?php echo $stats['with_tithi']; ?></h4>
                                    <p class="mb-0">With Tithi</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card stats-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-star fa-2x mb-2"></i>
                                    <h4><?php echo $stats['festivals']; ?></h4>
                                    <p class="mb-0">Festivals</p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="card stats-card">
                                <div class="card-body text-center">
                                    <i class="fas fa-calendar-day fa-2x mb-2"></i>
                                    <h4><?php echo $stats['earliest'] !== 'N/A' ? date('M d', strtotime($stats['earliest'])) : 'N/A'; ?></h4>
                                    <p class="mb-0">Date Range</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- CSV Upload Section -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5><i class="fas fa-upload"></i> Upload CSV File</h5>
                        </div>
                        <div class="card-body">
                            <?php if ($upload_message): ?>
                                <div class="alert alert-<?php echo $upload_status === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show" role="alert">
                                    <?php echo $upload_message; ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            <?php endif; ?>

                            <form method="POST" action="../api/panchang_management.php" enctype="multipart/form-data" id="fileUploadForm">
                                <input type="hidden" name="action" value="upload-csv">
                                <div class="upload-area">
                                    <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                    <h5>Choose CSV or JSON file or drag & drop here</h5>
                                    <p class="text-muted">Supports CSV and JSON files with Date, Tithi, Nakshatra, Yoga, Karana, etc.</p>
                                    <input type="file" name="csv_file" class="form-control" accept=".csv,.json" required>
                                    <div class="form-check mt-3">
                                        <input class="form-check-input" type="checkbox" id="clear_existing_upload" name="clear_existing">
                                        <label class="form-check-label" for="clear_existing_upload">
                                            Clear existing data before import
                                        </label>
                                    </div>
                                    <button type="submit" class="btn btn-primary mt-3">
                                        <i class="fas fa-upload"></i> Upload File
                                    </button>
                                </div>
                            </form>

                            <div class="mt-3">
                                <button class="btn btn-outline-info" onclick="showBackupModal()">
                                    <i class="fas fa-save"></i> Create Backup
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Sample JSON Section -->
                    <div class="card">
                        <div class="card-header">
                            <h5><i class="fas fa-code"></i> Sample JSON Format</h5>
                        </div>
                        <div class="card-body">
                            <p>Use this format for importing panchang data:</p>
                            <pre class="bg-light p-3 rounded" style="max-height: 300px; overflow-y: auto;"><code>[
    {
        "date": "2025-01-01",
        "tithi": "शुक्ल पक्ष - प्रतिपदा",
        "nakshatra": "अश्विनी",
        "yoga": "विष्कुम्भ",
        "karana": "बव",
        "muhurat": "ब्रह्म मुहूर्त",
        "rahu_kaal": "7:30 AM - 9:00 AM",
        "gulika_kaal": "3:00 PM - 4:30 PM",
        "sunrise": "07:00 AM",
        "sunset": "06:00 PM",
        "moonrise": "08:00 PM",
        "moonset": "08:00 AM",
        "special_day": "नव वर्ष",
        "festival": "नव वर्ष",
        "remarks": "शुभ दिन"
    },
    {
        "date": "2025-01-02",
        "tithi": "शुक्ल पक्ष - द्वितीया",
        "nakshatra": "भरणी",
        "yoga": "प्रीति",
        "karana": "बालव",
        "muhurat": "सूर्योदय मुहूर्त",
        "rahu_kaal": "3:00 PM - 4:30 PM",
        "gulika_kaal": "12:00 PM - 1:30 PM",
        "sunrise": "07:01 AM",
        "sunset": "06:01 PM",
        "moonrise": "09:00 PM",
        "moonset": "09:00 AM",
        "special_day": "",
        "festival": "",
        "remarks": ""
    }
]</code></pre>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle"></i>
                                <strong>Note:</strong> All fields are optional except 'date'. Use empty strings for missing values.
                            </div>
                            
                        </div>
                    </div>

                    <!-- Panchang Data Table -->
                    <div class="card">
                        <div class="card-header">
                            <h5><i class="fas fa-table"></i> Panchang Data</h5>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table id="panchangTable" class="table table-striped table-hover">
                                    <thead class="table-dark">
                                        <tr>
                                            <th>Date</th>
                                            <th>Tithi</th>
                                            <th>Nakshatra</th>
                                            <th>Yoga</th>
                                            <th>Karana</th>
                                            <th>Special Day</th>
                                            <th>Festival</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($panchang_data as $entry): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($entry['date']); ?></td>
                                            <td><?php echo htmlspecialchars($entry['tithi'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($entry['nakshatra'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($entry['yoga'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($entry['karana'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($entry['special_day'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($entry['festival'] ?? ''); ?></td>
                                            <td>
                                                <button class="btn btn-sm btn-primary btn-action" onclick="editEntry('<?php echo $entry['date']; ?>')">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-sm btn-danger btn-action" onclick="deleteEntry('<?php echo $entry['date']; ?>')">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                                <button class="btn btn-sm btn-info btn-action" onclick="viewDetails('<?php echo $entry['date']; ?>')">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Entry Modal -->
    <div class="modal fade" id="entryModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">Add Panchang Entry</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="entryForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Date *</label>
                                    <input type="date" class="form-control" id="entryDate" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Tithi *</label>
                                    <input type="text" class="form-control" id="entryTithi" placeholder="e.g., Shukla Paksha - Pratipada" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Nakshatra</label>
                                    <input type="text" class="form-control" id="entryNakshatra" placeholder="e.g., Ashwini">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Yoga</label>
                                    <input type="text" class="form-control" id="entryYoga" placeholder="e.g., Vishkumbha">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Karana</label>
                                    <input type="text" class="form-control" id="entryKarana" placeholder="e.g., Bava">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">Muhurat</label>
                                    <input type="text" class="form-control" id="entryMuhurat" placeholder="e.g., Brahma Muhurat">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Rahu Kaal</label>
                                    <input type="text" class="form-control" id="entryRahuKaal" placeholder="e.g., 7:30 AM - 9:00 AM">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Gulika Kaal</label>
                                    <input type="text" class="form-control" id="entryGulikaKaal" placeholder="e.g., 3:00 PM - 4:30 PM">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Special Day</label>
                                    <input type="text" class="form-control" id="entrySpecialDay" placeholder="e.g., New Year">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Festival</label>
                                    <input type="text" class="form-control" id="entryFestival" placeholder="e.g., Diwali">
                                </div>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Remarks</label>
                            <textarea class="form-control" id="entryRemarks" rows="3" placeholder="Additional notes..."></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="saveEntry()">Save Entry</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Backup Modal -->
    <div class="modal fade" id="backupModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create Backup</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>This will create a backup of all current Panchang data.</p>
                    <div class="mb-3">
                        <label class="form-label">Backup Description</label>
                        <input type="text" class="form-control" id="backupDescription" placeholder="e.g., Monthly backup - January 2025">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="createBackup()">Create Backup</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
        $(document).ready(function() {
            $('#panchangTable').DataTable({
                pageLength: 25,
                order: [[0, 'desc']],
                responsive: true
            });
        });

        function showAddEntryModal() {
            $('#modalTitle').text('Add Panchang Entry');
            $('#entryForm')[0].reset();
            $('#entryModal').modal('show');
        }

        function editEntry(date) {
            // Fetch entry data and populate form
            $('#modalTitle').text('Edit Panchang Entry');
            $('#entryDate').val(date);
            // TODO: Populate other fields with existing data
            $('#entryModal').modal('show');
        }

        function deleteEntry(date) {
            if (confirm('Are you sure you want to delete this entry?')) {
                // TODO: Implement delete functionality
                alert('Delete functionality to be implemented');
            }
        }

        function viewDetails(date) {
            // TODO: Implement view details functionality
            alert('View details functionality to be implemented');
        }

        function saveEntry() {
            // TODO: Implement save functionality
            alert('Save functionality to be implemented');
        }

        function showBackupModal() {
            $('#backupModal').modal('show');
        }

        function createBackup() {
            // TODO: Implement backup functionality
            alert('Backup functionality to be implemented');
        }

        function exportToJSON() {
            // TODO: Implement JSON export
            alert('JSON export functionality to be implemented');
        }

        // File Upload Form Handling
        $('#fileUploadForm').on('submit', function(e) {
            e.preventDefault();
            
            const fileInput = $(this).find('input[type="file"]')[0];
            const file = fileInput.files[0];
            
            if (!file) {
                alert('Please select a file');
                return;
            }
            
            // Show loading
            const submitBtn = $(this).find('button[type="submit"]');
            const originalText = submitBtn.html();
            submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Uploading...').prop('disabled', true);
            
            // Create FormData
            const formData = new FormData();
            formData.append('action', 'upload-csv');
            formData.append('csv_file', file);
            formData.append('clear_existing', $(this).find('#clear_existing_upload').is(':checked') ? 1 : 0);
            
            // Submit form
            $.ajax({
                url: '../api/panchang_management.php',
                method: 'POST',
                dataType: 'json',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    console.log('Upload Response:', response);
                    if (response.success) {
                        alert('File uploaded successfully! ' + response.success_count + ' entries added.');
                        location.reload();
                    } else {
                        alert('Error: ' + (response.error || 'Unknown error'));
                    }
                },
                error: function(xhr, status, error) {
                    console.log('Upload Error Status:', status);
                    console.log('Upload Error:', error);
                    console.log('Response Text:', xhr.responseText);
                    
                    let errorMessage = 'Upload error: ' + error;
                    if (xhr.responseText) {
                        try {
                            const errorResponse = JSON.parse(xhr.responseText);
                            errorMessage = 'Server error: ' + (errorResponse.error || xhr.responseText);
                        } catch (e) {
                            errorMessage = 'Server error: ' + xhr.responseText;
                        }
                    }
                    alert(errorMessage);
                },
                complete: function() {
                    submitBtn.html(originalText).prop('disabled', false);
                }
            });
        });

    </script>
</body>
</html> 