<?php
defined('BASEPATH') or exit('No direct script access allowed');

class NotificationController extends CI_Controller
{
    protected $Notification = 'Notification';

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->library('session');
        $this->load->helper('auth');
        $this->load->library('firebase');
        $this->load->model('admin/User_model');
        $this->load->model('admin/Content_model');


        check_admin();
    }
    public function notifications()
    {

        $docs = $this->firebase->getCollection('Notification');

        $events = $this->Content_model->getAllEvents();

        $notifications = [];

        foreach ($docs as $id => $data) {
            $notifications[] = [
                'id'        => $id,
                'title'     => $data['title'] ?? '',
                'message'   => $data['message'] ?? '',
                'type'      => $data['type'] ?? '',
                'timestamp' => $data['timestamp'] ?? 0
            ];
        }

        // newest first
        usort($notifications, fn($a, $b) => $b['timestamp'] <=> $a['timestamp']);

        $data['notifications'] = $notifications;
        $data['events'] = $events;
        $data['page_title'] = 'notification';
        $data['active_menu'] = 'notification';
        $data['content_view'] = 'admin/pages/notifications';


        $this->load->view('admin/layouts/main', $data);
    }
    public function sendNotification()
    {
        $input = json_decode(file_get_contents('php://input'), true);

        $recipientType = $input['recipientType'] ?? 'all';
        $eventId = $input['eventId'] ?? null;

        $title = trim($input['subject'] ?? '');
        $message = trim($input['message'] ?? '');
        $eventUserIds = $this->Content_model->getEventUsers($eventId);

        if (!$title || !$message) {
            echo json_encode(['status' => 'error', 'message' => 'Subject and message required']);
            return;
        }

        // $users = $this->User_model->getAllUsers();
        $users = $this->User_model->getUsersByIds($eventUserIds);

        $userIds = array_column($users, 'id');



        $sent = 0;
        $skipped = 0;
        $timestamp = round(microtime(true) * 1000);

        // 1. Save ONE notification document
        $notificationData = [
            'user_ids'  => $userIds,
            'title'     => $title,
            'message'   => $message,
            'type'      => 'event',
            'timestamp' => (int)$timestamp
        ];

        $this->firebase->setDocument('Notification', $notificationData, (string)$timestamp);

        // 2. Send push to each user
        foreach ($users as $user) {
            if ($recipientType === 'active' && ($user['status'] ?? '') !== 'Active') continue;
            if ($recipientType === 'inactive' && ($user['status'] ?? '') !== 'Inactive') continue;

            if (!empty($user['token'])) {
                $response = $this->firebase->sendFCMNotification($user['token'], $title, $message);
                if ($response && isset($response['name'])) $sent++;
            } else {
                $skipped++;
            }
        }

        echo json_encode(['status' => 'success']);
    }
    // In NotificationController.php
    public function deleteNotification($id = null)
    {
        if (!$id) {
            echo json_encode(['status' => 'error', 'message' => 'Notification ID required']);
            return;
        }

        $deleted = $this->firebase->deleteDocument('Notification', $id);

        if ($deleted) {
            echo json_encode(['status' => 'success', 'message' => 'Notification deleted']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Failed to delete notification']);
        }
    }
    // In NotificationController.php
    public function testFCMNotification()
    {
        $testToken = 'e7CgfJn0xUzShqK3mxv0I7:APA91bH8dh_rHlUV_PGoC9y9VTAxzANvHb8UKPFe7aioghKgYWLchquctZtqCRQ1XRsn1unTT6wiJtrJOOPC6CUQ8lMF4E6gl28gxL5N24T0w2E--TeIEWY';
        $title     = 'Test Notification';
        $body      = 'This is a test notification.';

        // Send notification via Firebase library
        $response = $this->firebase->sendFCMNotification(
            $testToken,
            $title,
            $body
        );

        // Show response for debugging
        if ($response) {
            echo '<pre>';
            echo "Notification sent successfully. Response:\n";
            print_r($response);
            echo '</pre>';
        } else {
            echo '<pre>';
            print_r($response);
            echo '</pre>';
        }
    }
}
