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

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

use Google\Cloud\Firestore\FirestoreClient;

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

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

    /**
     * Display all tick requests
     */
    public function requests()
    {
        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 users from Firebase
            $allUsers = $this->customer_model->getall_customer();
            
            // Filter users with tickRequestStatus = "Request"
            $tickRequests = array();
            if (isset($allUsers['user'])) {
                foreach ($allUsers['user'] as $userId => $user) {
                    if (isset($user['tickRequestStatus']) && $user['tickRequestStatus'] === 'Request') {
                        $tickRequests[$userId] = $user;
                    }
                }
            }
            
            // Sort by request date if available, otherwise by joinDate
            if (!empty($tickRequests)) {
                uasort($tickRequests, function($a, $b) {
                    $aDate = isset($a['tickRequestDate']) ? $a['tickRequestDate'] : (isset($a['joinDate']) ? $a['joinDate'] : 0);
                    $bDate = isset($b['tickRequestDate']) ? $b['tickRequestDate'] : (isset($b['joinDate']) ? $b['joinDate'] : 0);
                    return $bDate - $aDate; // Newest first
                });
            }
            
            // Apply search filter
            if (!empty($searchText)) {
                $filtered = array();
                foreach ($tickRequests as $userId => $user) {
                    if (stripos($user['fullName'], $searchText) !== false || 
                        stripos($user['email'], $searchText) !== false ||
                        (isset($user['userName']) && stripos($user['userName'], $searchText) !== false)) {
                        $filtered[$userId] = $user;
                    }
                }
                $data['tickRequests'] = $filtered;
            } else {
                $data['tickRequests'] = $tickRequests;
            }

            $this->global['pageTitle'] = 'StreamAdmin : Blue Tick Requests';
            $this->loadViews("tick/requests", $this->global, $data, NULL);
        }
    }

    /**
     * View verified users (those who have blue tick)
     */
    public function verified()
    {
        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 users
            $allUsers = $this->customer_model->getall_customer();
            
            // Filter verified users (tickRequestStatus = "approved" OR hasBlueCheck = true)
            $verifiedUsers = array();
            if (isset($allUsers['user'])) {
                foreach ($allUsers['user'] as $userId => $user) {
                    if ((isset($user['tickRequestStatus']) && $user['tickRequestStatus'] === 'approved') ||
                        (isset($user['hasBlueCheck']) && $user['hasBlueCheck'] === true)) {
                        $verifiedUsers[$userId] = $user;
                    }
                }
            }
            
            // Apply search filter
            if (!empty($searchText)) {
                $filtered = array();
                foreach ($verifiedUsers as $userId => $user) {
                    if (stripos($user['fullName'], $searchText) !== false || 
                        stripos($user['email'], $searchText) !== false ||
                        (isset($user['userName']) && stripos($user['userName'], $searchText) !== false)) {
                        $filtered[$userId] = $user;
                    }
                }
                $data['verifiedUsers'] = $filtered;
            } else {
                $data['verifiedUsers'] = $verifiedUsers;
            }

            $this->global['pageTitle'] = 'StreamAdmin : Verified Users';
            $this->loadViews("tick/verified", $this->global, $data, NULL);
        }
    }

    /**
     * View rejected requests
     */
    public function rejected()
    {
        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 users
            $allUsers = $this->customer_model->getall_customer();
            
            // Filter rejected requests (tickRequestStatus = "Rejected")
            $rejectedUsers = array();
            if (isset($allUsers['user'])) {
                foreach ($allUsers['user'] as $userId => $user) {
                    if (isset($user['tickRequestStatus']) && $user['tickRequestStatus'] === 'Rejected') {
                        $rejectedUsers[$userId] = $user;
                    }
                }
            }
            
            // Sort by rejection date
            if (!empty($rejectedUsers)) {
                uasort($rejectedUsers, function($a, $b) {
                    $aDate = isset($a['tickRejectedDate']) ? $a['tickRejectedDate'] : 0;
                    $bDate = isset($b['tickRejectedDate']) ? $b['tickRejectedDate'] : 0;
                    return $bDate - $aDate;
                });
            }
            
            // Apply search filter
            if (!empty($searchText)) {
                $filtered = array();
                foreach ($rejectedUsers as $userId => $user) {
                    if (stripos($user['fullName'], $searchText) !== false || 
                        stripos($user['email'], $searchText) !== false ||
                        (isset($user['userName']) && stripos($user['userName'], $searchText) !== false)) {
                        $filtered[$userId] = $user;
                    }
                }
                $data['rejectedUsers'] = $filtered;
            } else {
                $data['rejectedUsers'] = $rejectedUsers;
            }

            $this->global['pageTitle'] = 'StreamAdmin : Rejected Tick Requests';
            $this->loadViews("tick/rejected", $this->global, $data, NULL);
        }
    }

    /**
     * View single tick request details
     */
    public function viewRequest($userId = NULL)
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
        } else {
            if ($userId == null) {
                redirect('tick/requests');
            }

            $data['userInfo'] = $this->customer_model->get_customerdetails($userId);
            $data['userId'] = $userId;

            $this->global['pageTitle'] = 'StreamAdmin : Tick Request Details';
            $this->loadViews("tick/viewRequest", $this->global, $data, NULL);
        }
    }

    /**
     * Approve blue tick request
     */
    public function approveRequest()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $userId = $this->input->post('userId');
            $email = $this->input->post('email');
            $note = $this->security->xss_clean($this->input->post('note'));

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

            $currentTime = time() * 1000;

            $updateData = array(
                'old' => array('email' => $email),
                'new' => array(
                    'hasBlueCheck' => true,
                    'tickRequestStatus' => 'approved',
                    'userStatus' => 'approved',
                    'tickApprovedDate' => $currentTime,
                    'tickApprovalNote' => !empty($note) ? $note : ''
                )
            );

            $result = $this->customer_model->update_customer($updateData);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Blue tick approved successfully')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to approve tick request')));
            }
        }
    }

    /**
     * Reject blue tick request
     */
    public function rejectRequest()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $userId = $this->input->post('userId');
            $email = $this->input->post('email');
            $reason = $this->security->xss_clean($this->input->post('reason'));

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

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

            $currentTime = time() * 1000;

            $updateData = array(
                'old' => array('email' => $email),
                'new' => array(
                    'hasBlueCheck' => false,
                    'tickRequestStatus' => 'Rejected',
                    'userStatus' => 'rejected',
                    'tickRejectedDate' => $currentTime,
                    'tickRejectionReason' => $reason
                )
            );

            $result = $this->customer_model->update_customer($updateData);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Tick request rejected')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to reject request')));
            }
        }
    }

    /**
     * Revoke blue tick
     */
    public function revokeTick()
    {
        if (!$this->isAdmin()) {
            echo (json_encode(array('status' => 'access')));
        } else {
            $userId = $this->input->post('userId');
            $email = $this->input->post('email');
            $reason = $this->security->xss_clean($this->input->post('reason'));

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

            $currentTime = time() * 1000;

            $updateData = array(
                'old' => array('email' => $email),
                'new' => array(
                    'hasBlueCheck' => false,
                    'tickRequestStatus' => 'Rejected',
                    'userStatus' => 'rejected',
                    'tickRevokedDate' => $currentTime,
                    'tickRevocationReason' => !empty($reason) ? $reason : 'Verification revoked by admin'
                )
            );

            $result = $this->customer_model->update_customer($updateData);

            if ($result) {
                echo (json_encode(array('status' => TRUE, 'message' => 'Blue tick revoked successfully')));
            } else {
                echo (json_encode(array('status' => FALSE, 'message' => 'Failed to revoke tick')));
            }
        }
    }
}

