<?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" enctype="multipart/form-data">
                                <div class="upload-area">
                                    <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                                    <h5>Choose CSV file or drag & drop here</h5>
                                    <p class="text-muted">Supports CSV files with Date, Tithi, Nakshatra, Yoga, Karana, etc.</p>
                                    <input type="file" name="csv_file" class="form-control" accept=".csv" required>
                                    <button type="submit" class="btn btn-primary mt-3">
                                        <i class="fas fa-upload"></i> Upload CSV
                                    </button>
                                </div>
                            </form>

                            <div class="mt-3">
                                <a href="../api/panchang_management.php?action=download-csv" class="btn btn-outline-primary">
                                    <i class="fas fa-download"></i> Download Current CSV
                                </a>
                                <button class="btn btn-outline-success" onclick="exportToJSON()">
                                    <i class="fas fa-file-code"></i> Export to JSON
                                </button>
                                <button class="btn btn-outline-info" onclick="showBackupModal()">
                                    <i class="fas fa-save"></i> Create Backup
                                </button>
                            </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');
        }
    </script>
</body>
</html> 