<?php
$page_title = "Notifications";
include 'template.php';
include 'includes/fcm_helper.php';

// Handle form submission
$success_msg = "";
$error_msg = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_notification'])) {
    $title   = trim($_POST['notif_title'] ?? '');
    $message = trim($_POST['notif_message'] ?? '');
    $recipient_type = $_POST['recipient_type'] ?? 'all';
    $specific_user_id = $_POST['specific_user_id'] ?? null;
    $image_url = trim($_POST['notif_image'] ?? '');

    // Handle Image Upload
    if (isset($_FILES['notif_image_file']) && $_FILES['notif_image_file']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = '../assets/images/notifications/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        $file_extension = pathinfo($_FILES['notif_image_file']['name'], PATHINFO_EXTENSION);
        $filename = 'notif_' . time() . '_' . uniqid() . '.' . $file_extension;
        $target_file = $upload_dir . $filename;

        if (move_uploaded_file($_FILES['notif_image_file']['tmp_name'], $target_file)) {
            // DYNAMIC URL GENERATION: Detects the path automatically
            $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
            $host = $_SERVER['HTTP_HOST'];
            $request_uri = $_SERVER['REQUEST_URI'];
            $admin_pos = strpos($request_uri, '/admin/');
            $base_folder_path = substr($request_uri, 0, $admin_pos);
            $image_url = $protocol . "://" . $host . $base_folder_path . "/assets/images/notifications/" . $filename;
        }
    }

    if (empty($title) || empty($message)) {
        $error_msg = "Title and message are required.";
    } elseif ($recipient_type === 'specific' && empty($specific_user_id)) {
        $error_msg = "Please select a specific user.";
    } else {
        // Insert the notification
        $stmt = $conn->prepare("INSERT INTO notifications (title, message, image_url) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $title, $message, $image_url);

        if ($stmt->execute()) {
            $notifId = $stmt->insert_id;
            $stmt->close();

            $count = 0;
            if ($recipient_type === 'all') {
                // Broadcast to ALL registered users
                $userResult = mysqli_query($conn, "SELECT id, fcm_token FROM users");
                $insertStmt = $conn->prepare(
                    "INSERT INTO user_notifications (user_id, notification_id) VALUES (?, ?)"
                );
                while ($user = mysqli_fetch_assoc($userResult)) {
                    $insertStmt->bind_param("ii", $user['id'], $notifId);
                    $insertStmt->execute();
                    if (!empty($user['fcm_token'])) {
                        sendFCMv1Notification($user['fcm_token'], $title, $message, $image_url);
                    }
                    $count++;
                }
                $insertStmt->close();
                $success_msg = "Notification sent to all $count users!";
            } else {
                // Send to specific user
                $insertStmt = $conn->prepare(
                    "INSERT INTO user_notifications (user_id, notification_id) VALUES (?, ?)"
                );
                $insertStmt->bind_param("ii", $specific_user_id, $notifId);
                $insertStmt->execute();
                $insertStmt->close();
                $count = 1;

                // Get user name and token for push
                $uStmt = $conn->prepare("SELECT name, fcm_token FROM users WHERE id = ?");
                $uStmt->bind_param("i", $specific_user_id);
                $uStmt->execute();
                $uResult = $uStmt->get_result();
                $uData = $uResult->fetch_assoc();
                $userName = $uData['name'] ?? 'User';
                if (!empty($uData['fcm_token'])) {
                    sendFCMv1Notification($uData['fcm_token'], $title, $message, $image_url);
                }
                $uStmt->close();

                $success_msg = "Notification sent to $userName!";
            }
        } else {
            $error_msg = "Failed to create notification: " . $conn->error;
        }
    }
}

// Fetch users for the specific user dropdown
$users_list = [];
$usersResult = mysqli_query($conn, "SELECT id, name, email FROM users ORDER BY name ASC");
if ($usersResult) {
    while ($row = mysqli_fetch_assoc($usersResult)) {
        $users_list[] = $row;
    }
}

// Fetch sent notifications history
$history = [];
$historyResult = mysqli_query($conn,
    "SELECT n.*, 
            (SELECT COUNT(*) FROM user_notifications WHERE notification_id = n.id) as recipient_count,
            (SELECT COUNT(*) FROM user_notifications WHERE notification_id = n.id AND is_read = 1) as read_count,
            (SELECT GROUP_CONCAT(u.name SEPARATOR ', ') FROM user_notifications un JOIN users u ON un.user_id = u.id WHERE un.notification_id = n.id) as recipient_names
     FROM notifications n 
     ORDER BY n.created_at DESC 
     LIMIT 50"
);
if ($historyResult) {
    while ($row = mysqli_fetch_assoc($historyResult)) {
        $history[] = $row;
    }
}
?>

<style>
    .notif-card {
        background: white;
        border-radius: 12px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.08);
        padding: 30px;
        margin-bottom: 30px;
    }
    .notif-card h4 {
        margin-bottom: 20px;
        color: #2c3e50;
    }
    .notif-card h4 i {
        color: #ff6b35;
        margin-right: 10px;
    }
    .form-control:focus {
        border-color: #ff6b35;
        box-shadow: 0 0 0 0.2rem rgba(255,107,53,0.15);
    }
    .btn-send {
        background: linear-gradient(135deg, #ff6b35, #e55a2b);
        border: none;
        color: white;
        padding: 12px 32px;
        border-radius: 8px;
        font-weight: 600;
        font-size: 16px;
        transition: all 0.3s;
    }
    .btn-send:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 15px rgba(255,107,53,0.4);
        color: white;
    }
    .history-item {
        border-left: 4px solid #ff6b35;
        padding: 15px 20px;
        margin-bottom: 15px;
        background: #f8f9fa;
        border-radius: 0 8px 8px 0;
        transition: all 0.2s;
    }
    .history-item:hover {
        background: #fff3ee;
    }
    .history-title {
        font-weight: 600;
        color: #2c3e50;
        font-size: 16px;
    }
    .history-message {
        color: #666;
        margin: 5px 0;
        font-size: 14px;
    }
    .history-meta {
        font-size: 12px;
        color: #999;
    }
    .history-meta span {
        margin-right: 15px;
    }
    .badge-sent {
        background: #e8f5e9;
        color: #2e7d32;
        padding: 3px 10px;
        border-radius: 12px;
        font-size: 12px;
    }
    .badge-read {
        background: #e3f2fd;
        color: #1565c0;
        padding: 3px 10px;
        border-radius: 12px;
        font-size: 12px;
    }
    .char-count {
        font-size: 12px;
        color: #999;
        text-align: right;
    }
    .empty-state {
        text-align: center;
        padding: 40px;
        color: #999;
    }
    .empty-state i {
        font-size: 48px;
        margin-bottom: 15px;
        color: #ddd;
    }
</style>

<h2 class="mb-4">
    <i class="fas fa-bell" style="color: #ff6b35;"></i> 
    Send Notifications
</h2>

<?php if ($success_msg): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<?php if ($error_msg): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($error_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<!-- SEND NOTIFICATION -->
<div class="notif-card">
    <h4><i class="fas fa-paper-plane"></i> Compose Notification</h4>
    <form method="POST" id="notifForm" enctype="multipart/form-data">
        <div class="mb-3">
            <label for="notif_title" class="form-label fw-semibold">Title</label>
            <input type="text" class="form-control" id="notif_title" name="notif_title" 
                   placeholder="e.g. New Collection Arrived! 🎉" maxlength="255" required>
            <div class="char-count"><span id="titleCount">0</span>/255</div>
        </div>
        <div class="mb-3">
            <label for="notif_message" class="form-label fw-semibold">Message</label>
            <textarea class="form-control" id="notif_message" name="notif_message" rows="4" 
                      placeholder="Write your notification message here..." maxlength="1000" required></textarea>
            <div class="char-count"><span id="msgCount">0</span>/1000</div>
        </div>
        
        <div class="mb-3">
            <label for="notif_image" class="form-label fw-semibold">Image URL (Optional)</label>
            <input type="url" class="form-control" id="notif_image" name="notif_image" 
                   placeholder="https://example.com/image.jpg" maxlength="1000">
            <small class="text-muted">Direct link to an image...</small>
        </div>

        <div class="mb-3">
            <label for="notif_image_file" class="form-label fw-semibold">OR Upload Image</label>
            <input type="file" class="form-control" id="notif_image_file" name="notif_image_file" accept="image/*">
            <small class="text-muted">Select an image from your computer.</small>
        </div>
        
        <div class="mb-4">
            <label class="form-label fw-semibold">Recipient</label>
            <div class="d-flex gap-4 mb-3">
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="recipient_type" id="typeAll" value="all" checked>
                    <label class="form-check-label" for="typeAll">
                        <i class="fas fa-broadcast-tower me-1"></i> All Users
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="recipient_type" id="typeSpecific" value="specific">
                    <label class="form-check-label" for="typeSpecific">
                        <i class="fas fa-user me-1"></i> Specific User
                    </label>
                </div>
            </div>
            
            <div id="specificUserField" style="display: none;">
                <label for="specific_user_id" class="form-label small">Select User</label>
                <select class="form-control" name="specific_user_id" id="specific_user_id">
                    <option value="">-- Choose User --</option>
                    <?php foreach ($users_list as $user): ?>
                        <option value="<?php echo $user['id']; ?>">
                            <?php echo htmlspecialchars($user['name']); ?> (<?php echo htmlspecialchars($user['email']); ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
                <input type="text" id="userFilter" class="form-control mt-2 form-control-sm" placeholder="Search user by name or email...">
            </div>
        </div>

        <div class="d-flex justify-content-between align-items-center">
            <small class="text-muted" id="recipientHint">
                <i class="fas fa-info-circle"></i> This will be sent to all registered users.
            </small>
            <button type="submit" name="send_notification" class="btn btn-send" id="sendBtn">
                <i class="fas fa-paper-plane me-2"></i>Send Notification
            </button>
        </div>
    </form>
</div>

<!-- NOTIFICATION HISTORY -->
<div class="notif-card">
    <h4><i class="fas fa-history"></i> Sent Notifications</h4>
    
    <?php if (empty($history)): ?>
        <div class="empty-state">
            <i class="fas fa-bell-slash d-block"></i>
            <p>No notifications sent yet.</p>
        </div>
    <?php else: ?>
        <?php foreach ($history as $notif): ?>
            <div class="history-item">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="history-title"><?php echo htmlspecialchars($notif['title']); ?></div>
                    <div>
                        <span class="badge-sent">
                            <i class="fas fa-users"></i> <?php echo $notif['recipient_count']; ?> 
                            <?php echo $notif['recipient_count'] == 1 ? 'recipient' : 'recipients'; ?>
                        </span>
                        <span class="badge-read">
                            <i class="fas fa-eye"></i> <?php echo $notif['read_count']; ?> read
                        </span>
                    </div>
                </div>
                <div class="history-message"><?php echo nl2br(htmlspecialchars($notif['message'])); ?></div>
                <?php if (!empty($notif['image_url'])): ?>
                    <div class="mt-2">
                        <img src="<?php echo htmlspecialchars($notif['image_url']); ?>" alt="Notification Image" 
                             style="max-width: 200px; max-height: 120px; border-radius: 8px; border: 1px solid #ddd;">
                    </div>
                <?php endif; ?>
                <div class="history-meta">
                    <span><i class="fas fa-clock"></i> <?php echo date('d M Y, h:i A', strtotime($notif['created_at'])); ?></span>
                    <?php if ($notif['recipient_count'] > 0 && $notif['recipient_count'] <= 3): ?>
                        <span><i class="fas fa-user-tag"></i> To: <?php echo htmlspecialchars($notif['recipient_names']); ?></span>
                    <?php elseif ($notif['recipient_count'] > 3): ?>
                        <span><i class="fas fa-user-tag"></i> To: Multiple Users</span>
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<script>
// Character counters
document.getElementById('notif_title').addEventListener('input', function() {
    document.getElementById('titleCount').textContent = this.value.length;
});
document.getElementById('notif_message').addEventListener('input', function() {
    document.getElementById('msgCount').textContent = this.value.length;
});

// Recipient type toggle
const specificField = document.getElementById('specificUserField');
const recipientHint = document.getElementById('recipientHint');
const typeAll = document.getElementById('typeAll');
const typeSpecific = document.getElementById('typeSpecific');

typeAll.addEventListener('change', function() {
    if (this.checked) {
        specificField.style.display = 'none';
        recipientHint.innerHTML = '<i class="fas fa-info-circle"></i> This will be sent to all registered users.';
    }
});

typeSpecific.addEventListener('change', function() {
    if (this.checked) {
        specificField.style.display = 'block';
        recipientHint.innerHTML = '<i class="fas fa-info-circle"></i> This will be sent only to the selected user.';
    }
});

// User list filtering
document.getElementById('userFilter').addEventListener('input', function() {
    const term = this.value.toLowerCase();
    const select = document.getElementById('specific_user_id');
    const options = select.options;
    
    for (let i = 1; i < options.length; i++) {
        const text = options[i].text.toLowerCase();
        options[i].style.display = text.includes(term) ? '' : 'none';
    }
});

// Confirm before sending
document.getElementById('notifForm').addEventListener('submit', function(e) {
    const isAll = typeAll.checked;
    const msg = isAll ? 'Send this notification to ALL registered users?' : 'Send this notification to the selected user?';
    if (!confirm(msg)) {
        e.preventDefault();
    }
});
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</div></body></html>

