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

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class Onesignal extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        if (notAllow('pwa-push', ['feature', 'active'], true)):
            redirect(base_url('dashboard'));
            exit();
        endif;
        is_login();
        $data = array();
        $data['page_title'] = "Onesignal";
        $data['page'] = "Settings";
        $data['settings'] = $this->common_m->get_user_settings(auth('id'));

        $settings = $this->common_m->get_user_settings(auth('id'));
        $notification = !empty($settings['onesignal_config']) ? json_decode($settings['onesignal_config']) : "";
        if (isset($notification) && !empty($notification)):
            $data['allUsers'] = $this->get_player_id($notification);
        endif;
        $data['main_content'] = $this->load->view('backend/users/onesignal', $data, TRUE);
        $this->load->view('backend/index', $data);
    }

    public function add_notification()
    {
        is_login();
        is_test();
        $this->form_validation->set_rules('onsignal_app_id', 'onsignal_app_id', 'trim|xss_clean');
        $this->form_validation->set_rules('user_auth_key', 'user_auth_key', 'trim|xss_clean');
        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect($_SERVER['HTTP_REFERER']);
        } else {
            $is_onsignal_active = $this->input->post('is_active_onsignal', TRUE);
            $is_order_push = $this->input->post('is_order_push', TRUE);
            $is_call_waiter_push = $this->input->post('is_call_waiter_push', TRUE);
            $onsignal = array(
                'onsignal_app_id' => $this->input->post('onsignal_app_id', TRUE),
                'user_auth_key' => $this->input->post('user_auth_key', TRUE),
                'user_id' => $this->input->post('user_id', TRUE),
                'is_active_onsignal' => isset($is_onsignal_active) ? $is_onsignal_active : 0,
                'is_order_push' => isset($is_order_push) ? 1 : 0,
                'is_call_waiter_push' => isset($is_call_waiter_push) ? 1 : 0,
            );
            $data = array(
                'onesignal_config' => json_encode($onsignal),
            );

            if (check() != 1):
                exit();
            endif;


            $id = $this->input->post('id');
            if ($id == 0) {
                $insert = $this->admin_m->insert($data, 'user_settings');
            } else {
                $insert = $this->admin_m->update($data, $id, 'user_settings');
            }

            if ($insert) {
                $this->session->set_flashdata('success', !empty(lang('success_text')) ? lang('success_text') : 'Save Change Successful');
                redirect($_SERVER['HTTP_REFERER']);
            } else {
                $this->session->set_flashdata('error', !empty(lang('error_text')) ? lang('error_text') : 'Somethings Were Wrong!!');
                redirect($_SERVER['HTTP_REFERER']);
            }
        }
    }

    public function get_users($user_id, $auth_id)
    {
        $find = $this->common_m->find_subscribers($user_id, $auth_id);
        if ($find == 0) {
            $this->common_m->insert(['user_id' => $user_id, 'auth_id' => $auth_id, 'created_at' => d_time()], 'subscriber_list');
        }
        echo json_encode(['st' => 1, 'userId' => $user_id]);
    }

    public function send_notification()
    {
        // Feature access check
        if (notAllow('pwa-push', ['feature', 'active'], true)):
            redirect(base_url('dashboard'));
            exit();
        endif;

        is_test();

        // Form validation
        $this->form_validation->set_rules('headings', 'Headings', 'trim|required');
        $this->form_validation->set_rules('msg', 'Message', 'trim|required');
        $this->form_validation->set_rules('user_id[]', __('subscribers_list'), 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->session->set_flashdata('error', validation_errors());
            redirect(base_url('admin/onesignal'));
            return;
        }

        // Safely get input
        $headings = $this->input->post('headings', true);
        $msg      = $this->input->post('msg', true);
        $appId    = $this->input->post('app_id', true);
        $url      = $this->input->post('url', true);
        $userIds  = $this->input->post('user_id', true); // Should be array

        if (!is_array($userIds) || empty($userIds)) {
            $this->session->set_flashdata('error', lang('error_text'));
            redirect(base_url('admin/onesignal'));
            return;
        }

        // Fetch OneSignal config
        $settings = $this->common_m->get_user_settings(auth('id'));
        if (empty($settings['onesignal_config'])) {
            $this->session->set_flashdata('error', 'onesignal_config_missing');
            redirect(base_url("admin/onesignal"));
            return;
        }

        $notification = json_decode($settings['onesignal_config']);
        if (json_last_error() !== JSON_ERROR_NONE || empty($notification->user_auth_key)) {
            $this->session->set_flashdata('error', 'invalid_onesignal_config');
            redirect(base_url("admin/onesignal"));
            return;
        }

        // Prepare payload
        $payload = [
            'app_id'             => $appId,
            'include_player_ids' => $userIds,
            'data'               => ['foo' => 'bar'],
            'contents'           => ['en' => $msg],
            'headings'           => ['en' => $headings],
            'url'                => !empty($url) ? $url : base_url(auth('username')),
        ];

        // Initialize Guzzle client
        $client = new Client([
            'base_uri' => 'https://onesignal.com/api/v1/',
            'timeout'  => 30,
            'headers'  => [
                'Content-Type'  => 'application/json; charset=utf-8',
                'Authorization' => 'Basic ' . $notification->user_auth_key,
            ],
        ]);

        try {
            $response = $client->post('notifications', [
                'json' => $payload,
            ]);

            $body = json_decode($response->getBody()->getContents(), true);



            if (!empty($body['id'])) {
                $this->session->set_flashdata('success', lang('success_text'));
            } else {
                log_message('error', 'OneSignal: Unexpected response body: ' . print_r($body, true));
                $this->session->set_flashdata('error', 'notification_send_failed');
            }
        } catch (ConnectException $e) {
            $this->session->set_flashdata('error', 'notification_network_error');
        } catch (RequestException $e) {
            $response = $e->getResponse();
            if ($response) {
                $statusCode = $response->getStatusCode();
                $body = json_decode($response->getBody()->getContents(), true);
                echo "<pre>";
                print_r($body);
                exit();
            } else {
                echo "<pre>";
                print_r($e->getMessage());
                exit();
            }
            $this->session->set_flashdata('error', lang('notification_send_failed'));
        } catch (\Exception $e) {
            echo "<pre>";
            print_r($e->getMessage());
            exit();
        }

        redirect(base_url("admin/onesignal"));
    }

    public function get_player_id($notification)
    {
        if (check() != 1):
            exit();
        endif;
        require_once('vendor/autoload.php');

        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request('GET', "https://onesignal.com/api/v1/players?app_id={$notification->onsignal_app_id}&limit=100&offset=0", [
                'headers' => [
                    'Accept' => 'text/plain',
                    'Authorization' => 'Basic ' . $notification->user_auth_key,
                ],
            ]);
            $result = json_decode($response->getBody(), TRUE);
        } catch (Exception $e) {
        }

        $ids = [];
        if (isset($result) && !empty($result)):
            foreach ($result['players'] as $key => $row) {
                $ids[] = $row['id'];
            }
        endif;
        return !empty($ids) ? $ids : [];
    }
}
