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

// Get all users for notification targeting
$stmt = $pdo->query("SELECT id, name, mobile, city FROM users ORDER BY name");
$users = $stmt->fetchAll();

    // Get recent notifications (handle case where table might not exist)
    $recent_notifications = [];
    try {
        $stmt = $pdo->query("
            SELECT pn.*, u.name as user_name 
            FROM push_notifications pn 
            LEFT JOIN users u ON pn.user_id = u.id 
            ORDER BY pn.created_at DESC 
            LIMIT 10
        ");
        $recent_notifications = $stmt->fetchAll();
    } catch (Exception $e) {
        // Table doesn't exist yet, show empty list
        $recent_notifications = [];
    }

// Handle form submission
$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $title = trim($_POST['title'] ?? '');
        $body = trim($_POST['body'] ?? '');
        $target_type = $_POST['target_type'] ?? 'all';
        $user_ids = $_POST['user_ids'] ?? [];
        
        if (empty($title) || empty($body)) {
            throw new Exception('Title and message are required');
        }
        
        $pdo = getDBConnection();
        
        if ($target_type === 'all') {
            // Send to all users
            $stmt = $pdo->query("SELECT id, device_token FROM users WHERE device_token IS NOT NULL AND device_token != ''");
            $target_users = $stmt->fetchAll();
        } else {
            // Send to specific users
            if (empty($user_ids)) {
                throw new Exception('Please select at least one user');
            }
            $placeholders = str_repeat('?,', count($user_ids) - 1) . '?';
            $stmt = $pdo->prepare("SELECT id, device_token FROM users WHERE id IN ($placeholders) AND device_token IS NOT NULL AND device_token != ''");
            $stmt->execute($user_ids);
            $target_users = $stmt->fetchAll();
        }
        
        if (empty($target_users)) {
            throw new Exception('No users with valid device tokens found');
        }
        
        $success_count = 0;
        $failed_count = 0;
        
        foreach ($target_users as $user) {
            try {
                // Store notification in database
                $stmt = $pdo->prepare("
                    INSERT INTO push_notifications (
                        user_id, title, body, device_token, status, created_at
                    ) VALUES (?, ?, ?, ?, 'sent', CURRENT_TIMESTAMP)
                ");
                
                $stmt->execute([
                    $user['id'],
                    $title,
                    $body,
                    $user['device_token']
                ]);
                
                // Here you would integrate with Firebase Cloud Messaging (FCM)
                // For now, we'll simulate the FCM call
                
                $success_count++;
            } catch (Exception $e) {
                $failed_count++;
                error_log("Failed to send notification to user {$user['id']}: " . $e->getMessage());
            }
        }
        
        $message = "Notifications sent successfully! Success: $success_count, Failed: $failed_count";
        $message_type = 'success';
        
        // Refresh recent notifications
        $stmt = $pdo->query("
            SELECT pn.*, u.name as user_name 
            FROM push_notifications pn 
            LEFT JOIN users u ON pn.user_id = u.id 
            ORDER BY pn.created_at DESC 
            LIMIT 10
        ");
        $recent_notifications = $stmt->fetchAll();
        
    } catch (Exception $e) {
        $message = $e->getMessage();
        $message_type = 'danger';
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Push Notifications - 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">
    <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;
        }
        .notification-form {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        .user-checkbox {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 10px;
            margin: 5px 0;
        }
        .user-checkbox:hover {
            background: #e9ecef;
        }
        .notification-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .status-badge {
            font-size: 12px;
            padding: 4px 8px;
            border-radius: 12px;
        }
        .status-sent { background: #d4edda; color: #155724; }
        .status-failed { background: #f8d7da; color: #721c24; }
        .status-pending { background: #fff3cd; color: #856404; }
    </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" href="index.php">
                            <i class="fas fa-tachometer-alt me-2"></i> Dashboard
                        </a>
                        <a class="nav-link" href="users.php">
                            <i class="fas fa-users me-2"></i> Users
                        </a>
                        <a class="nav-link" href="appointments.php">
                            <i class="fas fa-calendar-check me-2"></i> Appointments
                        </a>
                        <a class="nav-link active" href="notifications.php">
                            <i class="fas fa-bell me-2"></i> Push Notifications
                        </a>
                        <a class="nav-link" href="settings.php">
                            <i class="fas fa-cog me-2"></i> Settings
                        </a>
                        <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><i class="fas fa-bell me-2"></i>Push Notifications</h2>
                        <span class="text-muted">Send notifications to your users</span>
                    </div>
                    
                    <?php if ($message): ?>
                        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                            <?php echo htmlspecialchars($message); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <div class="row">
                        <!-- Send Notification Form -->
                        <div class="col-lg-8">
                            <div class="notification-form">
                                <h4 class="mb-4">
                                    <i class="fas fa-paper-plane me-2"></i>Send New Notification
                                </h4>
                                
                                <form method="POST" id="notificationForm">
                                    <div class="mb-3">
                                        <label for="title" class="form-label">Notification Title *</label>
                                        <input type="text" class="form-control" id="title" name="title" 
                                               placeholder="Enter notification title" required>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label for="body" class="form-label">Notification Message *</label>
                                        <textarea class="form-control" id="body" name="body" rows="4" 
                                                  placeholder="Enter your message here" required></textarea>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">Target Users</label>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="target_type" 
                                                   id="targetAll" value="all" checked>
                                            <label class="form-check-label" for="targetAll">
                                                Send to all users
                                            </label>
                                        </div>
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="target_type" 
                                                   id="targetSpecific" value="specific">
                                            <label class="form-check-label" for="targetSpecific">
                                                Send to specific users
                                            </label>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3" id="userSelection" style="display: none;">
                                        <label class="form-label">Select Users</label>
                                        <div class="row">
                                            <?php foreach ($users as $user): ?>
                                                <div class="col-md-6">
                                                    <div class="user-checkbox">
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" 
                                                                   name="user_ids[]" value="<?php echo $user['id']; ?>" 
                                                                   id="user<?php echo $user['id']; ?>">
                                                            <label class="form-check-label" for="user<?php echo $user['id']; ?>">
                                                                <strong><?php echo htmlspecialchars($user['name']); ?></strong><br>
                                                                <small class="text-muted">
                                                                    <?php echo htmlspecialchars($user['mobile']); ?> - 
                                                                    <?php echo htmlspecialchars($user['city']); ?>
                                                                </small>
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                    
                                    <div class="d-grid">
                                        <button type="submit" class="btn btn-warning btn-lg">
                                            <i class="fas fa-paper-plane me-2"></i>Send Notification
                                        </button>
                                    </div>
                                </form>
                            </div>
                        </div>
                        
                        <!-- Recent Notifications -->
                        <div class="col-lg-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="fas fa-history me-2"></i>Recent Notifications
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($recent_notifications)): ?>
                                        <p class="text-muted">No notifications sent yet.</p>
                                    <?php else: ?>
                                        <?php foreach ($recent_notifications as $notification): ?>
                                            <div class="notification-card">
                                                <div class="d-flex justify-content-between align-items-start mb-2">
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($notification['title']); ?></h6>
                                                    <span class="status-badge status-<?php echo $notification['status']; ?>">
                                                        <?php echo ucfirst($notification['status']); ?>
                                                    </span>
                                                </div>
                                                <p class="mb-2"><?php echo htmlspecialchars($notification['body']); ?></p>
                                                <div class="d-flex justify-content-between align-items-center">
                                                    <small class="text-muted">
                                                        <?php echo $notification['user_name'] ? htmlspecialchars($notification['user_name']) : 'All Users'; ?>
                                                    </small>
                                                    <small class="text-muted">
                                                        <?php echo date('M d, H:i', strtotime($notification['created_at'])); ?>
                                                    </small>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </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>
    <script>
        // Show/hide user selection based on target type
        document.querySelectorAll('input[name="target_type"]').forEach(radio => {
            radio.addEventListener('change', function() {
                const userSelection = document.getElementById('userSelection');
                if (this.value === 'specific') {
                    userSelection.style.display = 'block';
                } else {
                    userSelection.style.display = 'none';
                    // Uncheck all user checkboxes
                    document.querySelectorAll('input[name="user_ids[]"]').forEach(checkbox => {
                        checkbox.checked = false;
                    });
                }
            });
        });
        
        // Form validation
        document.getElementById('notificationForm').addEventListener('submit', function(e) {
            const targetType = document.querySelector('input[name="target_type"]:checked').value;
            const userIds = document.querySelectorAll('input[name="user_ids[]"]:checked');
            
            if (targetType === 'specific' && userIds.length === 0) {
                e.preventDefault();
                alert('Please select at least one user when targeting specific users.');
                return false;
            }
        });
    </script>
</body>
</html> 