<?php
// Define admin access constant
define('ADMIN_ACCESS', true);

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();

// Initialize database tables if they don't exist
try {
    // Only initialize if not already done
    if (!function_exists('initializeDatabase')) {
        require_once '../config/database.php';
    }
    // Don't auto-initialize to prevent header issues
    // initializeDatabase();
} catch (Exception $e) {
    // Database initialization failed, continue with defaults
    error_log("Database initialization failed: " . $e->getMessage());
}

// Get current settings
$current_settings = [];
try {
    $settings_stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
    while ($row = $settings_stmt->fetch()) {
        $current_settings[$row['setting_key']] = $row['setting_value'];
    }
} catch (Exception $e) {
    // Settings table might not exist yet, use defaults
    $current_settings = [
        'app_version' => '1.0.0',
        'min_android_version' => '6.0',
        'min_ios_version' => '12.0',
        'maintenance_mode' => '0',
        'force_update' => '0',
        'system_enabled' => '1'
    ];
}

// Get statistics
$stats = [];

// Total users
$stmt = $pdo->query("SELECT COUNT(*) FROM users");
$stats['total_users'] = $stmt->fetchColumn();

// Total appointments
$stmt = $pdo->query("SELECT COUNT(*) FROM appointments");
$stats['total_appointments'] = $stmt->fetchColumn();

// Pending appointments
$stmt = $pdo->query("SELECT COUNT(*) FROM appointments WHERE status = 'pending'");
$stats['pending_appointments'] = $stmt->fetchColumn();

// Confirmed appointments
$stmt = $pdo->query("SELECT COUNT(*) FROM appointments WHERE status = 'confirmed'");
$stats['confirmed_appointments'] = $stmt->fetchColumn();

// Today's appointments
$stmt = $pdo->query("SELECT COUNT(*) FROM appointments WHERE appointment_date = CURDATE()");
$stats['today_appointments'] = $stmt->fetchColumn();

// Total revenue
$stmt = $pdo->query("SELECT SUM(amount) FROM appointments WHERE status != 'cancelled'");
$stats['total_revenue'] = $stmt->fetchColumn() ?: 0;

// Wallet statistics
try {
    $stmt = $pdo->query("SELECT COUNT(DISTINCT user_id) as total_wallet_users FROM wallet_transactions");
    $stats['total_wallet_users'] = $stmt->fetchColumn() ?: 0;
    
    $stmt = $pdo->query("SELECT SUM(CASE WHEN type = 'credit' THEN amount ELSE -amount END) as net_wallet_balance FROM wallet_transactions");
    $stats['net_wallet_balance'] = $stmt->fetchColumn() ?: 0;
    
    $stmt = $pdo->query("SELECT COUNT(*) as total_wallet_transactions FROM wallet_transactions");
    $stats['total_wallet_transactions'] = $stmt->fetchColumn() ?: 0;
} catch (Exception $e) {
    $stats['total_wallet_users'] = 0;
    $stats['net_wallet_balance'] = 0;
    $stats['total_wallet_transactions'] = 0;
}

// Recent appointments
$stmt = $pdo->query("
    SELECT a.*, u.name, u.mobile 
    FROM appointments a 
    JOIN users u ON a.user_id = u.id 
    ORDER BY a.created_at DESC 
    LIMIT 5
");
$recent_appointments = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Astro Admin Dashboard</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">
    <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, 193, 7, 0.2);
            color: #ffc107;
        }
        .main-content {
            background: #f8f9fa;
        }
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .stat-card.amber {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        .stat-card.green {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        .stat-card.blue {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
        .stat-card.purple {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .stat-card.teal {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        .appointment-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2 px-0">
                <div class="sidebar p-3">
                    <div class="text-center mb-4">
                        <h4 class="text-warning">
                            <i class="fas fa-star"></i> ASTRO ADMIN
                        </h4>
                    </div>
                    
                    <nav class="nav flex-column">
                        <a class="nav-link active" href="index.php">
                            <i class="fas fa-tachometer-alt me-2"></i> Dashboard
                        </a>
                        <li class="nav-item">
                            <a class="nav-link" href="appointments.php">
                                <i class="fas fa-calendar-check"></i> Appointments
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="users.php">
                                <i class="fas fa-users"></i> Users
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="notifications.php">
                                <i class="fas fa-bell"></i> Notifications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="panchang_management.php">
                                <i class="fas fa-calendar-alt"></i> Panchang Management
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="wallet_management.php">
                                <i class="fas fa-wallet"></i> Wallet Management
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="settings.php">
                                <i class="fas fa-cog"></i> Settings
                            </a>
                        </li>
                        <a class="nav-link" href="logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i> Logout
                        </a>
                    </nav>
                </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>Dashboard Overview</h2>
                        <span class="text-muted">Welcome back, Admin!</span>
                    </div>
                    
                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-md-4 col-lg-3">
                            <div class="stat-card">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3><?php echo $stats['total_users']; ?></h3>
                                        <p class="mb-0">Total Users</p>
                                    </div>
                                    <i class="fas fa-users fa-2x"></i>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4 col-lg-3">
                            <div class="stat-card amber">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3><?php echo $stats['total_appointments']; ?></h3>
                                        <p class="mb-0">Total Appointments</p>
                                    </div>
                                    <i class="fas fa-calendar-check fa-2x"></i>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4 col-lg-3">
                            <div class="stat-card green">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3><?php echo $stats['pending_appointments']; ?></h3>
                                        <p class="mb-0">Pending</p>
                                    </div>
                                    <i class="fas fa-clock fa-2x"></i>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4 col-lg-3">
                            <div class="stat-card blue">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3>₹<?php echo number_format($stats['total_revenue']); ?></h3>
                                        <p class="mb-0">Total Revenue</p>
                                    </div>
                                    <i class="fas fa-rupee-sign fa-2x"></i>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4 col-lg-3">
                            <div class="stat-card purple">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3><?php echo $stats['total_wallet_users']; ?></h3>
                                        <p class="mb-0">Wallet Users</p>
                                    </div>
                                    <i class="fas fa-wallet fa-2x"></i>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4 col-lg-3">
                            <div class="stat-card teal">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h3>₹<?php echo number_format($stats['net_wallet_balance'], 2); ?></h3>
                                        <p class="mb-0">Net Wallet Balance</p>
                                    </div>
                                    <i class="fas fa-balance-scale fa-2x"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Quick Actions -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="fas fa-bolt me-2"></i>Quick Actions
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex gap-3">
                                        <a href="notifications.php" class="btn btn-warning">
                                            <i class="fas fa-bell me-2"></i>Send Push Notification
                                        </a>
                                        <a href="appointments.php" class="btn btn-primary">
                                            <i class="fas fa-calendar-check me-2"></i>Manage Appointments
                                        </a>
                                        <a href="users.php" class="btn btn-success">
                                            <i class="fas fa-users me-2"></i>View Users
                                        </a>
                                        <a href="wallet_management.php" class="btn btn-purple">
                                            <i class="fas fa-wallet me-2"></i>Wallet Management
                                        </a>
                                        <a href="settings.php" class="btn btn-info">
                                            <i class="fas fa-cog me-2"></i>Launch Settings
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Launch Status -->
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="fas fa-rocket me-2 text-info"></i>Launch Status
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span>App Version:</span>
                                        <strong class="text-primary"><?php echo $current_settings['app_version'] ?? '1.0.0'; ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span>Maintenance Mode:</span>
                                        <span class="badge bg-<?php echo ($current_settings['maintenance_mode'] ?? '0') === '1' ? 'danger' : 'success'; ?>">
                                            <?php echo ($current_settings['maintenance_mode'] ?? '0') === '1' ? 'ON' : 'OFF'; ?>
                                        </span>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span>Force Update:</span>
                                        <span class="badge bg-<?php echo ($current_settings['force_update'] ?? '0') === '1' ? 'warning' : 'secondary'; ?>">
                                            <?php echo ($current_settings['force_update'] ?? '0') === '1' ? 'YES' : 'NO'; ?>
                                        </span>
                                    </div>
                                    <div class="text-center mt-3">
                                        <a href="settings.php" class="btn btn-sm btn-outline-info">
                                            <i class="fas fa-edit me-1"></i>Configure
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="fas fa-mobile-alt me-2 text-success"></i>Platform Support
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span>Android (Min):</span>
                                        <strong class="text-success"><?php echo $current_settings['min_android_version'] ?? '6.0'; ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span>iOS (Min):</span>
                                        <strong class="text-primary"><?php echo $current_settings['min_ios_version'] ?? '12.0'; ?></strong>
                                    </div>
                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                        <span>System Status:</span>
                                        <span class="badge bg-<?php echo ($current_settings['system_enabled'] ?? '1') === '1' ? 'success' : 'danger'; ?>">
                                            <?php echo ($current_settings['system_enabled'] ?? '1') === '1' ? 'ENABLED' : 'DISABLED'; ?>
                                        </span>
                                    </div>
                                    <div class="text-center mt-3">
                                        <a href="settings.php" class="btn btn-sm btn-outline-success">
                                            <i class="fas fa-cog me-1"></i>Settings
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <!-- Today's Appointments -->
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="fas fa-calendar-day me-2"></i>
                                        Today's Appointments (<?php echo $stats['today_appointments']; ?>)
                                    </h5>
                                </div>
                                <div class="card-body">
                                                                        <?php if ($stats['today_appointments'] > 0) { ?>
                                        <?php foreach ($recent_appointments as $appointment) { ?>
                                            <?php if (date('Y-m-d', strtotime($appointment['appointment_date'])) == date('Y-m-d')) { ?>
                                                <div class="appointment-card">
                                                    <div class="d-flex justify-content-between align-items-center">
                                                        <div>
                                                            <h6 class="mb-1"><?php echo htmlspecialchars($appointment['user_name']); ?></h6>
                                                            <small class="text-muted">
                                                                <?php echo $appointment['time_slot']; ?> • ₹<?php echo $appointment['amount']; ?>
                                                            </small>
                                                        </div>
                                                        <span class="badge bg-<?php 
                                                            if ($appointment['status'] == 'confirmed') {
                                                                echo 'success';
                                                            } elseif ($appointment['status'] == 'pending') {
                                                                echo 'warning';
                                                            } else {
                                                                echo 'danger';
                                                            }
                                                        ?>">
                                                            <?php echo ucfirst($appointment['status']); ?>
                                                        </span>
                                                    </div>
                                                </div>
                                            <?php } ?>
                                        <?php } ?>
                                    <?php } else { ?>
                                        <p class="text-muted text-center">No appointments for today</p>
                                    <?php } ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Recent Appointments -->
                        <div class="col-md-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="fas fa-history me-2"></i>
                                        Recent Appointments
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php foreach ($recent_appointments as $appointment) { ?>
                                        <div class="appointment-card">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <div>
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($appointment['user_name']); ?></h6>
                                                    <small class="text-muted">
                                                        <?php echo date('M d, Y', strtotime($appointment['appointment_date'])); ?> • 
                                                        <?php echo $appointment['time_slot']; ?>
                                                    </small>
                                                </div>
                                                <span class="badge bg-<?php 
                                                    if ($appointment['status'] == 'confirmed') {
                                                        echo 'success';
                                                    } elseif ($appointment['status'] == 'pending') {
                                                        echo 'warning';
                                                    } else {
                                                        echo 'danger';
                                                    }
                                                ?>">
                                                    <?php echo ucfirst($appointment['status']); ?>
                                                </span>
                                            </div>
                                        </div>
                                    <?php } ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Working Hours & Lunch Time -->
                        <div class="row mb-4">
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="fas fa-clock me-2 text-warning"></i>Working Hours
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <span>Start Time:</span>
                                            <strong class="text-primary"><?php echo $current_settings['start_time'] ?? '09:00'; ?></strong>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <span>End Time:</span>
                                            <strong class="text-primary"><?php echo $current_settings['end_time'] ?? '18:00'; ?></strong>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <span>Lunch Break:</span>
                                            <strong class="text-warning">
                                                <?php echo $current_settings['lunch_start'] ?? '13:00'; ?> - <?php echo $current_settings['lunch_end'] ?? '14:00'; ?>
                                            </strong>
                                        </div>
                                        <div class="text-center mt-3">
                                            <a href="settings.php" class="btn btn-sm btn-outline-warning">
                                                <i class="fas fa-edit me-1"></i>Configure
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="mb-0">
                                            <i class="fas fa-calendar-check me-2 text-info"></i>Booking Settings
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <span>Advance Booking:</span>
                                            <strong class="text-info"><?php echo $current_settings['advance_booking_days'] ?? '30'; ?> days</strong>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <span>Slot Duration:</span>
                                            <strong class="text-info"><?php echo $current_settings['slot_duration'] ?? '60'; ?> minutes</strong>
                                        </div>
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <span>Slots/Hour:</span>
                                            <strong class="text-info"><?php echo $current_settings['slots_per_hour'] ?? '1'; ?></strong>
                                        </div>
                                        <div class="text-center mt-3">
                                            <a href="settings.php" class="btn btn-sm btn-outline-info">
                                                <i class="fas fa-cog me-1"></i>Settings
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html> 