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

require APPPATH . '/libraries/BaseController.php';

use Google\Cloud\Firestore\FirestoreClient;

class Announcement extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('announcement_model');
        $this->load->helper('url');
    }

    public function index()
    {
        $this->announcements();
    }

    /**
     * Display all announcements
     */
    public function announcements()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $searchText = '';
            if (!empty($this->input->post('searchText'))) {
                $searchText = $this->security->xss_clean($this->input->post('searchText'));
            }
            $data['searchText'] = $searchText;

            // Get all announcements from Firebase
            $allAnnouncements = $this->announcement_model->getall_announcements();
            
            // Sort by createdDate descending (newest first)
            if (!empty($allAnnouncements)) {
                uasort($allAnnouncements, function($a, $b) {
                    $aDate = isset($a['createdDate']) ? $a['createdDate'] : 0;
                    $bDate = isset($b['createdDate']) ? $b['createdDate'] : 0;
                    return $bDate - $aDate;
                });
            }
            
            // Filter announcements based on search text if provided
            if (!empty($searchText)) {
                $filtered = array();
                foreach ($allAnnouncements as $key => $announcement) {
                    if (stripos($announcement['title'], $searchText) !== false || 
                        stripos($announcement['description'], $searchText) !== false) {
                        $filtered[$key] = $announcement;
                    }
                }
                $data['announcements'] = $filtered;
            } else {
                $data['announcements'] = $allAnnouncements;
            }

            $this->global['pageTitle'] = 'StreamAdmin : Announcements';
            $this->loadViews("announcements/announcements", $this->global, $data, NULL);
        }
    }

    /**
     * Display add announcement form
     */
    public function addAnnouncement()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->global['pageTitle'] = 'StreamAdmin : Add New Announcement';
            $this->loadViews("announcements/addAnnouncement", $this->global, NULL, NULL);
        }
    }

    /**
     * Add new announcement
     */
    public function addNewAnnouncement()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->load->library('form_validation');

            $this->form_validation->set_rules('title', 'Title', 'trim|required|max_length[200]');
            $this->form_validation->set_rules('description', 'Description', 'trim|required');

            if ($this->form_validation->run() == FALSE) {
                $this->addAnnouncement();
            } else {
                $title = $this->security->xss_clean($this->input->post('title'));
                $description = $this->security->xss_clean($this->input->post('description'));
                $sendNotification = $this->input->post('sendNotification') === '1' ? true : false;

                $currentTime = time() * 1000; // Convert to milliseconds
                
                $announcementInfo = array(
                    'title' => $title,
                    'description' => $description,
                    'createdDate' => $currentTime
                );

                $result = $this->announcement_model->add_announcement($announcementInfo);

                if ($result) {
                    // If send notification is checked, send push notifications to all users
                    if ($sendNotification) {
                        $this->sendNotificationToAllUsers($title, $description);
                    }
                    
                    $this->session->set_flashdata('success', 'Announcement created successfully' . ($sendNotification ? ' and notifications sent' : ''));
                } else {
                    $this->session->set_flashdata('error', 'Announcement creation failed');
                }

                redirect('announcement/announcements');
            }
        }
    }

    /**
     * View announcement details
     */
    public function viewAnnouncement($announcementId = NULL)
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            if ($announcementId == null) {
                redirect('announcement/announcements');
            }

            $data['announcementInfo'] = $this->announcement_model->get_announcement($announcementId);
            $data['announcementId'] = $announcementId;

            $this->global['pageTitle'] = 'StreamAdmin : Announcement Details';
            $this->loadViews("announcements/viewAnnouncement", $this->global, $data, NULL);
        }
    }

    /**
     * Edit announcement form
     */
    public function editAnnouncement($announcementId = NULL)
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            if ($announcementId == null) {
                redirect('announcement/announcements');
            }

            $data['announcementInfo'] = $this->announcement_model->get_announcement($announcementId);
            $data['announcementId'] = $announcementId;

            $this->global['pageTitle'] = 'StreamAdmin : Edit Announcement';
            $this->loadViews("announcements/editAnnouncement", $this->global, $data, NULL);
        }
    }

    /**
     * Update announcement
     */
    public function updateAnnouncement()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            $this->load->library('form_validation');

            $announcementId = $this->input->post('announcementId');

            $this->form_validation->set_rules('title', 'Title', 'trim|required|max_length[200]');
            $this->form_validation->set_rules('description', 'Description', 'trim|required');

            if ($this->form_validation->run() == FALSE) {
                $this->editAnnouncement($announcementId);
            } else {
                $title = $this->security->xss_clean($this->input->post('title'));
                $description = $this->security->xss_clean($this->input->post('description'));
                $sendNotification = $this->input->post('sendNotification') === '1' ? true : false;

                $announcementData = array(
                    'title' => $title,
                    'description' => $description
                );

                $result = $this->announcement_model->update_announcement($announcementId, $announcementData);

                if ($result) {
                    // If send notification is checked, send push notifications to all users
                    if ($sendNotification) {
                        $this->sendNotificationToAllUsers($title, $description);
                    }
                    
                    $this->session->set_flashdata('success', 'Announcement updated successfully' . ($sendNotification ? ' and notifications sent' : ''));
                } else {
                    $this->session->set_flashdata('error', 'Announcement update failed');
                }

                redirect('announcement/announcements');
            }
        }
    }

    /**
     * Delete announcement
     */
    public function deleteAnnouncement()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $announcementId = $this->input->post('announcementId');

            if (empty($announcementId)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Announcement ID is required')));
                return;
            }

            $result = $this->announcement_model->delete_announcement($announcementId);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Announcement deleted successfully')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to delete announcement')));
            }
        }
    }

    /**
     * Send notification to specific user
     */
    public function sendNotificationToUser()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $announcementId = $this->input->post('announcementId');
            $userId = $this->input->post('userId');

            if (empty($announcementId) || empty($userId)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Invalid data')));
                return;
            }

            $announcement = $this->announcement_model->get_announcement($announcementId);
            
            if (empty($announcement)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Announcement not found')));
                return;
            }

            // Get user token and send notification
            $result = $this->sendSingleNotification($userId, $announcement['title'], $announcement['description']);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Notification sent successfully')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to send notification')));
            }
        }
    }

    /**
     * Resend notification to all users
     */
    public function resendNotification()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $announcementId = $this->input->post('announcementId');

            if (empty($announcementId)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Announcement ID is required')));
                return;
            }

            $announcement = $this->announcement_model->get_announcement($announcementId);
            
            if (empty($announcement)) {
                echo (json_encode(array('status' => FALSE, 'message' => 'Announcement not found')));
                return;
            }

            $this->sendNotificationToAllUsers($announcement['title'], $announcement['description']);

            echo (json_encode(array('status' => TRUE, 'message' => 'Notifications sent to all users')));
        }
    }

    /**
     * Helper function to send notification to all users
     */
    private function sendNotificationToAllUsers($title, $description)
    {
        // Load customer model to get all user tokens
        $this->load->model('customer_model');
        $allUsers = $this->customer_model->getall_customer();
        
        $tokens = array();
        
        if (isset($allUsers['user'])) {
            foreach ($allUsers['user'] as $user) {
                if (isset($user['token']) && !empty($user['token'])) {
                    $tokens[] = $user['token'];
                }
            }
        }
        
        if (!empty($tokens)) {
            // Send Firebase Cloud Messaging notification
            $this->sendFCMNotification($tokens, $title, $description);
        }
    }

    /**
     * Helper function to send single notification
     */
    private function sendSingleNotification($userId, $title, $description)
    {
        $this->load->model('customer_model');
        $user = $this->customer_model->get_customerdetails($userId);
        
        if (isset($user['token']) && !empty($user['token'])) {
            return $this->sendFCMNotification(array($user['token']), $title, $description);
        }
        
        return false;
    }

    /**
     * Send FCM notification
     */
    private function sendFCMNotification($tokens, $title, $message)
    {
        // This is a placeholder - you'll need to implement FCM with your server key
        // You can use Firebase Admin SDK or HTTP API
        
        // Example using HTTP API:
        /*
        $serverKey = 'YOUR_FCM_SERVER_KEY';
        
        $data = array(
            'registration_ids' => $tokens,
            'notification' => array(
                'title' => $title,
                'body' => $message,
                'sound' => 'default',
                'badge' => '1'
            ),
            'data' => array(
                'type' => 'announcement',
                'title' => $title,
                'message' => $message
            )
        );
        
        $headers = array(
            'Authorization: key=' . $serverKey,
            'Content-Type: application/json'
        );
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        $result = curl_exec($ch);
        curl_close($ch);
        
        return $result;
        */
        
        // For now, just log that notification would be sent
        log_message('info', 'Notification would be sent: ' . $title . ' to ' . count($tokens) . ' users');
        return true;
    }
}

