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

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

class Site extends BaseController
{
    public $isApproved;

    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
        $this->load->model('login_model');
        $this->load->library('form_validation');

        $currentRole=$this->session->userdata('session_data')['role'];
        if(empty($currentRole)){
            redirect(base_url('login'));
        }
        // $authenthicate=$this->session->userdata('authenthicate');
        // if(!$authenthicate){
        //     redirect(base_url('login'));
        // }

    }
    public function addUserData(){
        $data=$this->input->post();
        $x=$this->common->addnewUser($data);

        echo  json_encode($x);
      
    }

    public function searchcomunity()
    {
        // $searchTerm=
        $userId = $this->session->userdata('userId');

        $searchTerm = $this->input->post('searchTerm');
        $forums = $this->db->like('title', $searchTerm)->or_like('content', $searchTerm)->get('forums')->result_array();;

        // Fetch user info for each forum post
        foreach ($forums as &$forum) {
            $forum['user'] = $this->user_model->getUserInfoById($forum['user_id']);
        }

        $data['current_user_id'] = $userId;
        $data['forumdata'] = $forums;
        $x = $this->load->view('seachforumlist', $data, TRUE);
        $jana['success'] = 1;
        $jana['output'] = $x;
        echo json_encode($jana);
    }

    public function searchUsers()
    {
        $myId = $this->session->userdata('userId');
        $searchTerm = $this->input->post('searchTerm');
        $userData = $this->user_model->searchUsers($searchTerm, $myId);
        echo (json_encode($userData));
    }

    public function index()
    {
        $dashboardData = $this->prepareDashboardData();
        $this->global['pageTitle'] = 'StreamAdmin : Dashboard';
        $this->loadViews('dashboard', $this->global, $dashboardData, NULL);
    }

    private function prepareDashboardData(): array
    {
        $this->load->model('customer_model');

        $userCollection = $this->customer_model->getall_customer();
        $users = isset($userCollection['user']) && is_array($userCollection['user']) ? $userCollection['user'] : [];

        $userStats = [
            'totalUsers'          => 0, // Will be calculated after filtering deleted users
            'activeUsers'         => 0,
            'suspendedUsers'      => 0,
            'warnedUsers'         => 0,
            'pendingApprovals'    => 0,
            'pendingVerification' => 0,
            'verifiedUsers'       => 0,
            'totalCoins'          => 0,
            'newThisWeek'         => 0,
            'warningsCount'       => 0,
            'tickRequestsCount'   => 0,
        ];

        $userLookup = [];
        $recentUsers = [];
        $topCreators = [];
        $tickRequests = [];

        $weekAgoMs = strtotime('-7 days') * 1000;
        $todayStart = strtotime('today');
        $todayEnd = $todayStart + 86400;

        foreach ($users as $userId => $user) {
            // Skip deleted users
            $isDeleted = isset($user['isDeleted']) ? (bool)$user['isDeleted'] : false;
            if ($isDeleted) {
                continue;
            }

            $userLookup[$userId] = $user;

            // Use new status field: active, warned, suspend
            $status = strtolower($user['status'] ?? 'active');
            $warningsCount = isset($user['warningCount']) ? (int)$user['warningCount'] : 0;
            $coins = isset($user['Earning']) ? (float)$user['Earning'] : 0.0;
            $joinDateMs = isset($user['createdDate']) ? (int)$user['createdDate'] : 0;
            $tickStatus = strtolower($user['tickRequestStatus'] ?? '');

            // Determine if user is active (active or warned status means they can still use the app)
            $isActive = ($status === 'active' || $status === 'warned');

            $userStats['totalCoins'] += $coins;
            
            // Count users by status
            if ($status === 'active') {
                $userStats['activeUsers']++;
            } elseif ($status === 'warning') {
                $userStats['warnedUsers']++;
            } elseif ($status === 'suspend') {
                $userStats['suspendedUsers']++;
            }
            
            if (isset($user['isApproved']) && $user['isApproved'] === false) {
                $userStats['pendingApprovals']++;
            }
            if ($warningsCount > 0) {
                $userStats['warningsCount']++;
            }
            if ($tickStatus === 'request' || (!empty($user['tickRequest']) && $user['tickRequest'] === true)) {
                $userStats['pendingVerification']++;
                $tickRequests[] = [
                    'id'         => $userId,
                    'name'       => $user['fullName'] ?? 'Unknown',
                    'userName'   => $user['userName'] ?? '',
                    'email'      => $user['email'] ?? '',
                    'followers'  => $user['followers'] ?? ($user['followersCount'] ?? 0),
                    'category'   => $user['category'] ?? ($user['primaryCategory'] ?? ''),
                    'requestDate'=> isset($user['lastActiveDate']) ? (int)$user['lastActiveDate'] : ($user['createdDate'] ?? 0),
                ];
            }
            if ($tickStatus === 'approved' || (!empty($user['hasBlueCheck']) && $user['hasBlueCheck'] === true)) {
                $userStats['verifiedUsers']++;
            }
            if ($tickStatus === 'request') {
                $userStats['tickRequestsCount']++;
            }

            if ($joinDateMs > 0) {
                if ($joinDateMs >= $weekAgoMs) {
                    $userStats['newThisWeek']++;
                }
                $recentUsers[] = [
                    'id'         => $userId,
                    'name'       => $user['fullName'] ?? 'Unknown',
                    'userName'   => $user['userName'] ?? '',
                    'joinDate'   => $joinDateMs,
                    'warnings'   => $warningsCount,
                    'isActive'   => $isActive,
                    'status'     => $status,
                    'hasBlueCheck'=> !empty($user['hasBlueCheck']),
                ];
            }

            $topCreators[] = [
                'id'       => $userId,
                'name'     => $user['fullName'] ?? 'Unknown',
                'userName' => $user['userName'] ?? '',
                'coins'    => $coins,
                'email'    => $user['email'] ?? '',
            ];
        }

        // Calculate total users (sum of all statuses, excluding deleted)
        $userStats['totalUsers'] = $userStats['activeUsers'] + $userStats['warnedUsers'] + $userStats['suspendedUsers'];

        $userStats['activeRate'] = $userStats['totalUsers'] > 0 ? round(($userStats['activeUsers'] / $userStats['totalUsers']) * 100, 1) : 0;
        $userStats['warningRate'] = $userStats['totalUsers'] > 0 ? round(($userStats['warnedUsers'] / $userStats['totalUsers']) * 100, 1) : 0;

        usort($recentUsers, function ($a, $b) {
            return $b['joinDate'] <=> $a['joinDate'];
        });
        $recentUsers = array_slice($recentUsers, 0, 6);

        usort($topCreators, function ($a, $b) {
            return $b['coins'] <=> $a['coins'];
        });
        $topCreators = array_values(array_filter($topCreators, function ($creator) {
            return $creator['coins'] > 0;
        }));
        $topCreators = array_slice($topCreators, 0, 5);

        usort($tickRequests, function ($a, $b) {
            return ($b['requestDate'] ?? 0) <=> ($a['requestDate'] ?? 0);
        });
        $tickRequests = array_slice($tickRequests, 0, 5);

        // Fetch users with status 'warned' instead of Warnings collection
        try {
            $warnedUsers = $this->common->readdatafromcollectionwhereclause('Users', 'status', '==', 'warning');
            $warnedUsers = is_array($warnedUsers) ? $warnedUsers : [];
        } catch (Exception $e) {
            log_message('error', 'Failed to fetch warned users: ' . $e->getMessage());
            $warnedUsers = [];
        }
        $warningSummary = $this->summarizeWarnings($warnedUsers, $todayStart, $todayEnd);

       $reports = $this->fetchCollection('Reports');
    
        $reportSummary = $this->summarizeReports($reports);

        $withdrawals = $this->fetchCollection('Withdraws');
        $transactionSummary = $this->summarizeTransactions($withdrawals, $userLookup, $todayStart, $todayEnd);

        $dailyTrend = $this->buildDailyTrend($users, $warnedUsers);

        $overviewCards = [
            [
                'title'       => 'Total Users',
                'value'       => $userStats['totalUsers'],
                'description' => $userStats['newThisWeek'] . ' joined this week',
                'icon'        => 'bi-people-fill',
                'variant'     => 'primary',
                'link'        => base_url('customer/customers'),
            ],
            [
                'title'       => 'Active Users',
                'value'       => $userStats['activeUsers'],
                'description' => $userStats['activeRate'] . '% active rate',
                'icon'        => 'bi-activity',
                'variant'     => 'success',
                'link'        => base_url('customer/active'),
            ],
            [
                'title'       => 'Warning Users',
                'value'       => $userStats['warnedUsers'],
                'description' => $userStats['warningsCount'] . ' warnings given',
                'icon'        => 'bi-shield-check',
                'variant'     => 'warning',
                'link'        => base_url('customer/warned'),
            ],
            
            [
                'title'       => 'Blue Tick Users',
                'value'       => $userStats['verifiedUsers'],
                'description' => $userStats['tickRequestsCount'] . ' blue tick requests',
                'icon'        => 'bi-patch-check',
                'variant'     => 'info',
                'link'        => base_url('tick/verified'),
            ],
        ];

        $currentUser = $this->session->userdata('session_data');
        $currentUserName = $currentUser['name'] ?? ($currentUser['fullName'] ?? 'Admin');

        return [
            'currentUserName'     => $currentUserName,
            'generatedAt'         => time(),
            'overview'            => [
                'cards'        => $overviewCards,
                'stats'        => $userStats,
                'totalCoins'   => $userStats['totalCoins'],
            ],
            'trend'              => $dailyTrend,
            'warnings'           => $warningSummary,
            'reports'            => $reportSummary,
            'transactions'       => $transactionSummary,
            'recentWarnings'     => array_slice($warningSummary['recent'], 0, 5),
            'recentTickRequests' => $tickRequests,
            'recentTransactions' => array_slice($transactionSummary['recent'], 0, 5),
            'topCreators'        => $topCreators,
            'recentUsers'        => $recentUsers,
        ];
    }

    private function fetchCollection(string $collectionName): array
    {
        try {
            $data = $this->common->readdatafromcollectionwhereclause($collectionName);
            return is_array($data) ? $data : [];
        } catch (Exception $e) {
            log_message('error', 'Failed to fetch collection ' . $collectionName . ': ' . $e->getMessage());
            return [];
        }
    }

    private function summarizeWarnings(array $warnedUsers, int $todayStart, int $todayEnd): array
    {
        $active = 0;
        $resolved = 0;
        $autoBlocksToday = 0;
        $sumWarningCount = 0;
        $recent = [];

        foreach ($warnedUsers as $userId => $user) {
            // Skip if user is not an array
            if (!is_array($user)) {
                continue;
            }

            // Skip deleted users
            $isDeleted = isset($user['isDeleted']) ? (bool)$user['isDeleted'] : false;
            if ($isDeleted) {
                continue;
            }

            $status = strtolower($user['status'] ?? 'warned');
            $warningCount = isset($user['warningCount']) ? (int)$user['warningCount'] : 0;
            $lastWarningAtMs = $user['lastWarningAt'] ?? ($user['updatedAt'] ?? 0);
            $lastWarningAt = $this->normalizeToSeconds($lastWarningAtMs);
            $sumWarningCount += $warningCount;

            // All warned users are considered active (since we're fetching only users with status 'warned')
            $active++;

            // Check if user was auto-blocked today (3+ warnings)
            if ($warningCount >= 3 && $lastWarningAt >= $todayStart && $lastWarningAt < $todayEnd) {
                $autoBlocksToday++;
            }

            $recent[] = [
                'id'            => $userId,
                'user'          => $user['email'] ?? ($user['userName'] ?? ($user['fullName'] ?? 'Unknown')),
                'userName'      => isset($user['userName']) ? (string)$user['userName'] : '',
                'fullName'      => isset($user['fullName']) ? (string)$user['fullName'] : '',
                'warningType'   => 'User Warning',
                'status'        => 'active',
                'occurrences'   => $warningCount,
                'lastOccurrence'=> $lastWarningAt,
            ];
        }

        usort($recent, function ($a, $b) {
            return ($b['lastOccurrence'] ?? 0) <=> ($a['lastOccurrence'] ?? 0);
        });

        $total = count($recent); // Total non-deleted warned users

        return [
            'total'          => $total,
            'active'         => $active,
            'resolved'       => $resolved,
            'autoBlocksToday'=> $autoBlocksToday,
            'averageSeverity'=> $total > 0 ? round($sumWarningCount / $total, 1) : 0,
            'recent'         => $recent,
        ];
    }

    private function summarizeReports(array $reports): array
    {
        $total = count($reports);
        $open = 0;
        $resolved = 0;
        $recent = [];

        foreach ($reports as $id => $report) {
            // Determine status based on actionTaken field
            $actionTaken = isset($report['actionTaken']) ? (bool)$report['actionTaken'] : false;
            
            if ($actionTaken) {
                $resolved++;
                $status = 'closed';
            } else {
                $open++;
                $status = 'open';
            }

            $createdAt = $this->normalizeToSeconds($report['timeStamp'] ?? ($report['timeStamp'] ?? ($report['timeStamp'] ?? 0)));
            $recent[] = [
                'id'        => $id,
                'title'     => $report['reportedUserName'] ?? ($report['reportedUserName'] ?? 'Report'),
                'reporter'  => $report['name'] ?? ($report['name'] ?? 'Unknown'),
                'status'    => $status,
                'createdAt' => $createdAt,
            ];
        }

        usort($recent, function ($a, $b) {
            return ($b['createdAt'] ?? 0) <=> ($a['createdAt'] ?? 0);
        });

        return [
            'total'    => $total,
            'open'     => $open,
            'resolved' => $resolved,
            'recent'   => array_slice($recent, 0, 5),
        ];
    }

    private function summarizeTransactions(array $withdrawals, array $userLookup, int $todayStart, int $todayEnd): array
    {
        $total = count($withdrawals);
        $pending = 0;
        $processedToday = 0;
        $recent = [];
        $startOfDayMs = $todayStart * 1000;
        $endOfDayMs = $todayEnd * 1000;

        foreach ($withdrawals as $id => $withdrawal) {
            $status = strtolower($withdrawal['status'] ?? 'pending');
            if ($status === 'pending') {
                $pending++;
            }
            if (isset($withdrawal['processedAt']) && $withdrawal['processedAt'] >= $startOfDayMs && $withdrawal['processedAt'] < $endOfDayMs) {
                $processedToday++;
            }

            $userId = $withdrawal['userId'] ?? null;
            $userData = $userId && isset($userLookup[$userId]) ? $userLookup[$userId] : [];

            $recent[] = [
                'id'        => $id,
                'amount'    => isset($withdrawal['amount']) ? (float)$withdrawal['amount'] : 0,
                'status'    => $status,
                'createdAt' => $withdrawal['createdAtMs'] ?? 0,
                'userName'  => $userData['fullName'] ?? ($withdrawal['userName'] ?? 'Unknown'),
                'userEmail' => $userData['email'] ?? ($withdrawal['userEmail'] ?? ($withdrawal['email'] ?? 'N/A')),
            ];
        }

        usort($recent, function ($a, $b) {
            return ($b['createdAt'] ?? 0) <=> ($a['createdAt'] ?? 0);
        });

        return [
            'total'          => $total,
            'pending'        => $pending,
            'processedToday' => $processedToday,
            'recent'         => $recent,
        ];
    }

    private function buildDailyTrend(array $users =[], array $warnedUsers=[]): array
    {
        $trend = [];

        for ($i = 6; $i >= 0; $i--) {
            $start = strtotime('-' . $i . ' days');
            $end = $start + 86400;
            $label = date('M j', $start);

            $startMs = $start * 1000;
            $endMs = $end * 1000;

            $newUsers = 0;
            foreach ($users as $user) {
                $joinDate = isset($user['createdDate']) ? (int)$user['createdDate'] : 0;
                if ($joinDate >= $startMs && $joinDate < $endMs) {
                    $newUsers++;
                }
            }

            $warningsCount = 0;
            foreach ($warnedUsers as $warning) {
                $lastOccurrence = $this->normalizeToSeconds($warning['lastWarningAt'] ?? ($warning['lastWarningAt'] ?? 0));
                if ($lastOccurrence >= $start && $lastOccurrence < $end) {
                    $warningsCount++;
                }
            }

            $trend[] = [
                'label'    => $label,
                'newUsers' => $newUsers,
                'warnings' => $warningsCount,
            ];
        }

        return $trend;
    }

    private function normalizeToSeconds($value): int
    {
        if (empty($value)) {
            return 0;
        }

        $value = (int)$value;
        if ($value > 1000000000000) {
            return (int)round($value / 1000);
        }

        return $value;
    }

     public function dashboard()
    {
            redirect(base_url('site/index'));
        
        //        $this->loadViews("questions");
    }
//accountr
    //addfinance
    public function addfinance()
    {
        $this->loadViews('addfinance');
    }
    //addmeeting
       public function addmeeting()
    {
        $this->loadViews('addmeeting');
    }
    //addreservations
       public function addreservations()
    {
        $data['units']=$this->common->readdatafromcollectionwhereclause('units');
        $data['Ammenities']=$this->common->readdatafromcollectionwhereclause('Ammenities');
        $this->loadViews('addreservations',$data);
    }
    //addsecurity
 
    //addsecurityofficer
    public function addsecurityofficer()
    {
        $this->loadViews('addsecurityofficer');
    }
    //addtemplte
        public function addtemplte()
    {
        $this->loadViews('addtemplte');
    }
    //adduser
            public function adduser()
    {
        $this->loadViews('adduser');
    }
    //addwarning
    public function addwarning()
    {
        $data['units']=$this->common->readdatafromcollectionwhereclause('units');
        $this->loadViews('addwarning',$data);
    }

public function sespenduser($id="")
{
    $firebase = $this->firebase->init();
		$db = $firebase->createDatabase();

		$auth = $firebase->createAuth();
        $auth->disableUser($id);
    $this->common->updatedatamodel('Users',$id,['approved'=>false]);
    $this->session->set_flashdata('success', 'User suspended successfully');
    redirect(base_url('site/users'));
}
public function activeuser($id="")
{   
    $firebase = $this->firebase->init();
    $db = $firebase->createDatabase();

    $auth = $firebase->createAuth();
    $auth->enableUser($id);
    $this->common->updatedatamodel('Users',$id,['approved'=>true]);
    $this->session->set_flashdata('success', 'User activated successfully');
    redirect(base_url('site/users'));
}

    public function addwarningdata() {
        try {
            $data = $this->input->post();
            $fileUrl="";
            $fileName="";
            if (!empty($_FILES['file']['name'])) {
                $firebase = $this->firebase->init();
                $storage = $firebase->createStorage();
                $defaultBucket = $storage->getBucket();

                $uploadedFile = $defaultBucket->upload(
                    file_get_contents($_FILES['file']['tmp_name']),
                    [
                        'name' => "warnings/" . time() . "_" . $_FILES['file']['name']
                    ]
                );
                $fileUrl = $uploadedFile->info()['mediaLink'];
                $fileName = $_FILES['file']['name'];
            }
             $unit=$data['units'];
             $warning_type=$data['warning_type'];
            $warning=$this->common->readdatafromcollectionbetween('Warnings','unitId',"==",$unit,'warningType',"==",$warning_type);
       
            if(count($warning)>0){
                $key=key($warning);

                $p=$warning[key($warning)];
                $p['occurrences']=$p['occurrences']+1;
                 $p['lastOccurrence']=time();
                 $p['updatedAt']=time();
                 $p['status']="active";
                 $p['comment']=$data['comment'];
                 $p['pdfName']=$fileName;
                 $p['pdfUrl']=$fileUrl;
                 $this->common->updatedatamodel('Warnings',$p['id'],$p);
                 $j['warningId']=$p['id'];
                 $j['createdAt']=time();
                 $j['warningType']=$warning_type;
                 $j['date']=$data['date'];
                 $j['dateMs']=strtotime($data['date'])*1000;
                 $j['comment']=$data['comment'];
                 $j['pdfName']=$fileName;
                 $j['pdfUrl']=$fileUrl;
                 $j['status']="active";
                 $k=time().rand().time();
                $this->common->addnextcollection('Warnings',$p['id'],"Occurrences",$k,$j);
                echo json_encode([
                    'success' => false,
                    'message' => 'warning already exists',
                    'warning'=>$p,
                    'occurrence'=>$k
                ]);
                exit;
            }else{
                $p['id']=time().rand().time();
                $p['unitId']=$unit;
                $p['warningType']=$warning_type;
                $p['date']=$data['date'];
                $p['dateMs']=strtotime($data['date'])*1000;
                $p['comment']=$data['comment'];
                $p['pdfName']=$fileName;
                $p['pdfUrl']=$fileUrl;
                $p['firstOccurrence']=time();
                $p['lastOccurrence']=time();
 
                $p['occurrences']=1;
                $p['status']="active";
                $p['updatedAt']=time();
               $this->common->adddatamodel('Warnings',$p['id'],$p);
               $j['warningId']=$p['id'];
               $j['createdAt']=time();
               $j['warningType']=$warning_type;
               $j['date']=$data['date'];
               $j['dateMs']=strtotime($data['date'])*1000;
               $j['comment']=$data['comment'];
               $j['pdfName']=$fileName;
               $j['pdfUrl']=$fileUrl;

               $j['status']="active";

               $this->common->addnextcollection('Warnings',$p['id'],"Occurrences",$p['id'],$j);

            
            

            }
            echo json_encode([
                'success' => true,
                'message' => 'Warning added successfully'
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }
    }
    //addwaterrates
   public function addwaterrates()
    {
        $this->loadViews('addwaterrates');
    }




    public function addwaterratesdata()
    {
        $data=$this->input->post();
        $data['id']=time().rand().time();
        $data['from']=(int)$data['from'];
        $data['to']=(int)$data['to'];
        $data['rate']=(int)$data['rate'];
        $data['currency']=$data['currency'];
        $this->common->adddatamodel('WaterRates',$data['id'],$data);
        $this->session->set_flashdata('success', 'Water Rate added successfully');
        redirect(base_url('site/waterrates'));
    }
    //admininfo
    public function admininfo()
    {
        $data['type']="admin";
        $data['admininfo']=$this->common->readdatafromcollectionwhereclause('AdminInfo');
        $this->loadViews('admininfo',$data);
    }
    public function addadmininfo()
    {
        $this->loadViews('addadmininfo');
    }
    public function addadmininfodata()
    {
        $data=$this->input->post();
        $data['role']="admin";
        $data['imageUrl']="";
        $res=$this->common->adddatawithauth('AdminInfo',$data);

        echo json_encode($res);
       
    }
    public function deleteadmininfo($id="")
    {
        $this->common->deletedatamodelwithauth('AdminInfo',$id);
        $this->session->set_flashdata('success', 'Admin Info deleted successfully');
        redirect(base_url('site/admininfo'));
    }
    public function updateadmininfo()
    {
        $data=$this->input->post();
        $res=$this->common->updatedatawithauth('AdminInfo',$data);

        echo json_encode($res);
    }

    public function bankinfo()
    {
        $data['type']="bank";
        $data['bankinfo']=$this->common->readdatafromcollectionwhereclause('BankAccounts');
        $this->loadViews('bankinfo',$data);
    }
    public function editbank($id="")
    {
        if($id==""){
            redirect(base_url('site/bankinfo'));
        }
        $data['type']="bank";
        $data['id']=$id;
        $data['bankinfo']=$this->common->readdatadocument('BankAccounts',$id);
        $this->loadViews('editbank',$data);
    }
    public function editbankdata($id="")
    {
        if($id==""){
            redirect(base_url('site/bankinfo'));
        }
        $data=$this->input->post();
        $this->common->updatedatamodel('BankAccounts',$id,$data);
        $this->session->set_flashdata('success', 'Bank Account updated successfully');
        redirect(base_url('site/bankinfo'));
    }
    public function deletebank($id="")
    {
        $this->common->deletedatamodel('BankAccounts',$id);
        $this->session->set_flashdata('success', 'Bank Account deleted successfully');
        redirect(base_url('site/bankinfo'));
    }

       public function condoinfo()
    {
        $data['type']="condo";
        $data['condoinfo']=$this->common->readdatafromcollectionwhereclause('CondoInfo');
    
        $this->loadViews('condoinfo',$data);
    }
    public function editcondoinfo($id="")
    {
        if($id==""){
            redirect(base_url('site/condoinfo'));
        }
        $data['type']="condo";
        $data['id']=$id;
        $data['condoinfo']=$this->common->readdatadocument('CondoInfo',$id);
        $this->loadViews('editcondoinfo',$data);
    }
    public function deletecondoinfo($id="")
    {
        $this->common->deletedatamodel('CondoInfo',$id);
        $this->session->set_flashdata('success', 'Condo Info deleted successfully');
        redirect(base_url('site/admininfo'));
    }
    public function editcondoinfodata($id="")
    {
        $data=$this->input->post();
        $this->common->updatedatamodel('CondoInfo',$id,$data);
        $this->session->set_flashdata('success', 'Condo Info updated successfully');
        redirect(base_url('site/condoinfo'));
    }
    //allsentmessage
    public function allsentmessage()
    {
        $data['messages']=$this->common->readdatafromcollectionwhereclause('Messages','status','sent');
        $this->loadViews('allsentmessage',$data);
    }
    //amenities
        public function amenities()
    {
        $data['amenities']=$this->common->readdatafromcollectionwhereclause('Ammenities');
        $this->loadViews('amenities',$data);
    }
    //authorization
    public function authorization()
    {
        $data['authorization']=$this->common->readdatadocument('Settings','AuthorizationTabSettings');
        $this->loadViews('authorization',$data);
    }

    public function updateAuthorizations()
    {
        $auth_types = $this->input->post('auth_types');
        $myarray=array();
        if(isset($auth_types['Employees'])){
            $myarray['Employees']=true;
        }else{
            $myarray['Employees']=false;
        }
        if(isset($auth_types['School_Bus'])){
            $myarray['School Bus']=true;
        }else{
            $myarray['School Bus']=false;
        }   
        if(isset($auth_types['Single_Entry'])){
            $myarray['Single Entry']=true;
        }else{
            $myarray['Single Entry']=false;
        }
        if(isset($auth_types['Express'])){
            $myarray['Express']=true;
        }else{
            $myarray['Express']=false;
        }
        if(isset($auth_types['Guests'])){
            $myarray['Guests']=true;
        }else{  
            $myarray['Guests']=false;
        }
        if(isset($auth_types['Visit_Log'])){
            $myarray['Visit Log']=true;
        }else{
            $myarray['Visit Log']=false;
        }           
        if(isset($auth_types['Permanent'])){
            $myarray['Permanent']=true;
        }else{
            $myarray['Permanent']=false;
        }   
        $j['tabFields']=$myarray;
        
        $this->common->updatedatamodel('Settings','AuthorizationTabSettings',$j);
      
        $this->session->set_flashdata('success', 'Authorization updated successfully');
        redirect(base_url('site/authorization'));
    }

    //bankaccounts
        public function bankaccounts()
    {
        $this->loadViews('bankaccounts');
    }
    //bannedpeople
    public function bannedpeople()
    {
        $data['units']=$this->common->readdatafromcollectionwhereclause('units');
        $data['bannedPeople']=$this->common->readdatafromcollectionwhereclause('BannedPeople');
        //echo "<pre>";
       // print_r($data);
        //echo "</pre>";
        $this->loadViews('bannedpeople',$data);

    }
    public function addbannedpost(){
        $data = $this->input->post();
      
        $fileUrl="";
        $fileName="";
        if (!empty($_FILES['file']['name'])) {
            $firebase = $this->firebase->init();
            $storage = $firebase->createStorage();
            $defaultBucket = $storage->getBucket();

            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['file']['tmp_name']),
                [
                    'name' => "warnings/" . time() . "_" . $_FILES['file']['name']
                ]
            );
            $fileUrl = $uploadedFile->info()['mediaLink'];
            $fileName = $_FILES['file']['name'];
        
        }
        $data['fileName']=$fileName;
        $data['fileUrl']=$fileUrl;
        $data['status']="banned";
        $data['id']="banned".rand().time();
    //   echo "<pre>";
    //   print_r($data);
    //   echo "</pre>";
    //   exit;
        $this->common->adddatamodel('BannedPeople',$data['id'],$data);
        $this->session->set_flashdata('success', 'Banned People Rate added successfully');
        redirect(base_url('site/bannedpeople'));

    }
    
    //billshistory
        public function billshistory()
    {
        $this->loadViews('billshistory');
    }
    
    public function boardofdirector()
    {
        $data['units']=$this->common->readdatafromcollectionwhereclause('units');
        $data['boardofdirector']=$this->common->readdatafromcollectionwhereclause('BoardOfDirectors');
        $this->loadViews('boardofdirector',$data);
    }
    public function editboardofdirector($id="")
    {
        $data=$this->input->post();
        $this->common->updatedatamodel('BoardOfDirectors',$id,$data);
        $this->session->set_flashdata('success', 'Board of Director updated successfully');
        redirect(base_url('site/boardofdirector'));
    }
    public function deleteboardofdirector($id="")
    {
        $this->common->deletedatamodel('BoardOfDirectors',$id);
        $this->session->set_flashdata('success', 'Board of Director deleted successfully');
        redirect(base_url('site/boardofdirector'));
    }
    public function addaccount()
    {
        $this->loadViews('addaccount');
    }

      public function accountspayables()
    {
        $this->loadViews('accountspayables');

        //        $this->loadViews("questions");
    }


    public function units()
    {
        $data['units']=$this->common->readdatafromcollectionwhereclause('units');
        // $this->loadViews('units',$data);
           $this->loadViews('units',$data);

        //        $this->loadViews("questions");
    }

    public function addguest()
    {
        $this->loadViews('addguest');
    }

    public function dorumdetail()
    {
        $this->loadViews('dorumdetail');
    }

    public function dorumexist()
    {
        $this->loadViews('dorumexist');
    }

    public function residents()
    {
        $this->loadViews('residents');
    }

    public function pets()
    {
        $data['pets']=$this->common->readdatafromcollectionwhereclause('Pets');
        $this->loadViews('pets',$data);
    }

    public function ammenties()
    {
        $this->loadViews('ammenties');
    }

    public function ammenityview()
    {
        $this->loadViews('ammenityview');
    }

    public function checklists()
    {
        
        $data['CheckLists']=$this->common->readdatafromcollectionwhereclause('CheckLists');
        $this->loadViews('checklists',$data);
    }

    //configuration
        public function configuration()
    {
        $this->loadViews('configuration');
    }
    //createcheck
            public function createcheck()
    {
        $this->loadViews('createcheck');
    }
    //createissue
               public function createissue()
    {
        $this->loadViews('createissue');
    }
    public function adddocument()
    {
        $firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();        
        $data=$this->input->post();

        if ($_FILES['file']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['file']['tmp_name']),
				[
					'name' => "file" . rand() . time() . $_FILES['file']['name'],
				]
			);


            $data['documentUrl']=$uploadedFile->info()['mediaLink'];
            $data['documentTitle']=$_FILES['file']['name'];
		}else{
            $data['documentUrl']="";
            $data['documentTitle']="";
        }
        $data['documentDate']=strtotime($data['date'])*1000;
       
        $data['id']=time().rand().time();
        $this->common->adddatamodel('Documents',$data['id'],$data);
        $this->session->set_flashdata('success', 'Document added successfully');
        if($data['category']=="Rule"){
            redirect(base_url('site/rules'));
        }elseif($data['category']=="Financial Statements"){
            redirect(base_url('site/financialstatements'));
        }elseif($data['category']=="Minutes"){
            redirect(base_url('site/minutes'));
        }elseif($data['category']=="Contracts"){
            redirect(base_url('site/contracts'));
        }
    }
    function deletedocument($id="")
    {
        $this->common->deletedatamodel('Documents',$id);
        $this->session->set_flashdata('success', 'Document deleted successfully');
        header('Location: ' . $_SERVER['HTTP_REFERER']);
        exit;
    }
    public function updatedocument($id="")
    {
        $data=$this->input->post();
        if ($_FILES['file']['tmp_name'] != '') {
            $firebase = $this->firebase->init();
            $storage = $firebase->createStorage();
            $defaultBucket = $storage->getBucket();
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['file']['tmp_name']),
                [
                    'name' => "file" . rand() . time() . $_FILES['file']['name'],
                ]
            );
            $data['documentUrl']=$uploadedFile->info()['mediaLink'];
            $data['documentTitle']=$_FILES['file']['name'];
        }
        $data['documentDate']=strtotime($data['date'])*1000;

        $this->common->updatedatamodel('Documents',$id,$data);
        $this->session->set_flashdata('success', 'Document updated successfully');
       if($data['category']=="Rule"){
        redirect(base_url('site/rules'));
       }elseif($data['category']=="Financial Statements"){
        redirect(base_url('site/financialstatements'));
       }elseif($data['category']=="Minutes"){
        redirect(base_url('site/minutes'));
       }elseif($data['category']=="Contracts"){
        redirect(base_url('site/contracts'));
       }
    }
    //dcuments
    public function rules()
    {
        $data['type']="Rule";
        $data['documents']=$this->common->readdatafromcollectionwhereclause('Documents','category','==','Rule');
        $this->loadViews('dcuments',$data);
    }
   
    public function minutes()
    {
        $data['type']="Minutes";
        $data['documents']=$this->common->readdatafromcollectionwhereclause('Documents','category','==','Minutes');
        $this->loadViews('dcuments',$data);
    }
    public function contracts() 
    {
        $data['type']="Contracts";
        $data['documents']=$this->common->readdatafromcollectionwhereclause('Documents','category','==','Contracts');
        $this->loadViews('dcuments',$data);
    }
    public function financialstatements()
    {
        $data['type']="Financial Statements";
        $data['documents']=$this->common->readdatafromcollectionwhereclause('Documents','category','==','Financial Statements');
        $this->loadViews('dcuments',$data);
    }
    
    //draft
        public function draft()
    {
        $this->loadViews('draft');
    }
    //editadmininfo
    public function editadmininfo($id="")
    {
        if($id==""){
            redirect(base_url('site/admininfo'));
        }
        $data['id']=$id;
        $data['admininfo']=$this->common->readdatadocument('AdminInfo',$id);
        $this->loadViews('editadmininfo',$data);
    }

    //editammenity
               public function editammenity($id="")
    {
        if($id==""){
            redirect(base_url('site/amenities'));
        }
        $data['amenity']=$this->common->readdatadocument('Ammenities',$id);
        $this->loadViews('editammenity',$data);
    }
    //editsecurityofficer
    public function editsecurityofficer()
    {
        $this->loadViews('editsecurityofficer');
    }
    //edituser
    public function edituser($userId = null)
    {
        
        if (!$userId) {
            redirect('site/users');
        }

        if ($this->input->server('REQUEST_METHOD') === 'POST') {
            // Handle form submission
            $userInfo = $this->input->post();

            $result = $this->common->updatedatamodel('Users', $userId, $userInfo);
            
            if ($result) {
                $this->session->set_flashdata('success', 'User updated successfully');
            } else {
                $this->session->set_flashdata('error', 'Failed to update user');
            }
            redirect('site/users');
        }

        // Get user data for display
        $d['id']=$userId;
        $d['userinfo'] = $this->common->readdatadocument('Users', $userId);
        //exit; 

        $this->loadViews('edituser', $d);
    }
    function   disableuser($userId)
    {
        $flag=$this->common->update_customerstatus($userId, "disable");
        if($flag){
            $this->common->updatedatamodel('Users', $userId, ['approved' => false]);
            $this->session->set_flashdata('success', 'User disabled successfully');
        }else{
            $this->session->set_flashdata('error', 'Failed to disable user');
        }
        redirect('site/users');
    }
    function   enableuser($userId)  
    {
        $flag=$this->common->update_customerstatus($userId, "enable");
        if($flag){
            $this->common->updatedatamodel('Users', $userId, ['approved' => true]);
            $this->session->set_flashdata('success', 'User enabled   successfully');
        }else{
            $this->session->set_flashdata('error', 'Failed to enable user');
        }
        redirect('site/users');
    }   
    
    //editwarning
        public function editwarning()
    {
        $this->loadViews('editwarning');
    }
    //editwaterrates
            public function editwaterrates($id="")
    {
        if($id==""){
            redirect(base_url('site/waterrates'));
        }
        $data['id']=$id;
        $data['waterRate']=$this->common->readdatadocument('WaterRates',$id);
        $this->loadViews('editwaterrates',$data);
    }
    public function editwaterratesdata($id="")
    {
        $data=$this->input->post();
        $data['rate']=(int)$data['rate'];   
        $data['from']=(int)$data['from'];
        $data['to']=(int)$data['to'];
        $data['currency']=$data['currency'];
        $this->common->updatedatamodel('WaterRates',$id,$data);
        $this->session->set_flashdata('success', 'Water Rate updated successfully');
        redirect(base_url('site/waterrates'));
    }
    //entandext
    public function entandext()
    {
        $data['AuthorizationEntries']=$this->common->readdatafromcollectionwhereclause('AuthorizationEntries');
        $this->loadViews('entandext',$data);
    }
    //eventjournal
        public function eventjournal()
    {
        
        $data['events']=$this->common->readdatafromcollectionwhereclause('EventJournal');
        $this->loadViews('eventjournal',$data);
    }
    public function addeventjournaldata()
    {
        $data=$this->input->post();
        $data['createdAt']=time()*1000;
        $data['id']=time().rand().time();
        $data['status']="Active";
        $data['userId']=$this->session->userdata('id');
        $data['reportedBy']="Admin";
        if($_FILES['file']['tmp_name']!=""){
            $firebase = $this->firebase->init();
            $storage = $firebase->createStorage();
            $defaultBucket = $storage->getBucket();
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['file']['tmp_name']),
                [
                    'name' => "file" . rand() . time() . $_FILES['file']['name'],
                ]
            );
            $data['attachmentUrl']=$uploadedFile->info()['mediaLink'];
            $data['attachmentName']=$_FILES['file']['name'];
        }else{
            $data['attachmentUrl']="";
            $data['attachmentName']="";
        }       

        $this->common->adddatamodel('EventJournal',$data['id'],$data);
        $this->session->set_flashdata('success', 'Event added successfully');
        redirect(base_url('site/eventjournal'));
    }
    public function vieweventjournal($id="")
    {
        $data['id']=$id;
        $data['event']=$this->common->readdatadocument('EventJournal',$id);
        $this->loadViews('vieweventjournal',$data);
    }
    //eventview
    public function eventview()
    {
        $this->loadViews('eventview');
    }
    public function checkview($id="")
    {
        if($id==""){
            redirect(base_url('site/checklists'));
        }
        $data['id']=$id;
        $data['checklist']=$this->common->readdatadocument('CheckLists',$id);
        $data['sreported']=$this->common->readdatafromcollectionwhereclause('SecurityReports','reportDocumentId','==',$id);
      
        $this->loadViews('checkview',$data);
    }
    //genbills
    public function genbills()
    {
        $this->loadViews('genbills');
    }
    //house
    public function house()
    {
        $this->loadViews('house');
    }
//issue
    public function issue()
    {
        $data['issues']=$this->common->readdatafromcollectionwhereclause('Issues');
        $this->loadViews('issue',$data);
    }
    public function editdraftmessagedata($id="")
    {
        $data=$this->input->post();
        $messageData = $this->_processMessageData($data, 'draft',$data['draft_id']);
        
      
        $this->common->updatedatamodel('Messages',$data['draft_id'],$data);
        $this->session->set_flashdata('success', 'Message updated successfully');
        redirect(base_url('site/messagecenter'));
    }
    //editdraftmessage
    public function editdraftmessage($id="")
    {
        $data['id']=$id;
        $data['message']=$this->common->readdatadocument('Messages',$id);
        $data['users']=$this->common->readdatafromcollectionwhereclause('Users');
        $this->loadViews('editdraftmessage',$data);
    }
    public function sendmessagedraftdata($id="")
    {
        $data=$this->input->post();
        
        
        $messageData = $this->_processMessageData($data, 'send',$data['draft_id']);
        if($data['send_time']=="immediately"){
            $data['status']="sent";
            $data['sentAt']=time()*1000;
        }else{
            $data['status']="scheduled";
            $data['scheduled_time']=strtotime($data['scheduled_time'])*1000;
        }
        $this->common->updatedatamodel('Messages',$data['draft_id'],$data);
        $this->session->set_flashdata('success', 'Message updated successfully');
        redirect(base_url('site/messagecenter'));
    }
    //messagecenter
        public function messagecenter()
    {
        $data['templates']=$this->common->readdatafromcollectionwhereclause('EmailTemplates');
        $data['messages']=$this->common->readdatafromcollectionwhereclauseorderby('Messages','sentAt','status','==','sent','5');
        $data['draftmessages']=$this->common->readdatafromcollectionwhereclauseorderby('Messages','createdAt','status','==','draft','5');
        // echo "<pre>";
        // print_r($data['messages']);
        // echo "</pre>";
        // exit;
        $this->loadViews('messagecenter',$data);
    }
    //newmessage
    public function newmessage()
    {
        $data['id']="";
        $data['users']=$this->common->readdatafromcollectionwhereclause('Users');
        $this->loadViews('newmessage',$data);
    }
    //usetemplate
    public function usetemplate($id="")
    {
        $data['id']=$id;
        $data['users']=$this->common->readdatafromcollectionwhereclause('Users');
        $data['template']=$this->common->readdatadocument('EmailTemplates',$id);
        $this->loadViews('usetemplate',$data);
    }
    //reports
   public function reports()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
            return;
        }

        $reportsRaw = $this->common->readdatafromcollectionwhereclause('Reports', 'actionTaken', '=', false);
      
        $reports = [];

        if (!empty($reportsRaw) && is_array($reportsRaw)) {
            foreach ($reportsRaw as $reportId => $report) {
                if (!is_array($report)) {
                    continue;
                }

                $report['id'] = $reportId;
                $report['reportedUserId'] = $report['reportedUserId'] ?? ($report['reportedUser']['id'] ?? '');
                $report['reportedUserEmail'] = $report['reportedUserEmail'] ?? ($report['reportedUser']['email'] ?? '');
                $report['reportedUserName'] = $report['reportedUserName'] ?? ($report['reportedUser']['name'] ?? '');
                $report['reporterUserId'] = $report['reporterUserId'] ?? ($report['reporter']['id'] ?? '');
                $report['reporterEmail'] = $report['reporterEmail'] ?? ($report['reporter']['email'] ?? '');
                $report['reporterName'] = $report['name'] ?? ($report['name'] ?? '');
                $report['reason'] = $report['reason'] ?? ($report['reasonText'] ?? '');
                $report['note'] = $report['note'] ?? ($report['notes'] ?? '');
                $report['createdAt'] = isset($report['createdAt']) ? (int)$report['createdAt'] : 0;
                $report['evidence'] = $report['evidence'] ?? ($report['evidenceUrl'] ?? ($report['mediaUrl'] ?? ''));

                $reports[] = $report;
            }
        }

        usort($reports, function ($a, $b) {
            return ($b['createdAt'] ?? 0) <=> ($a['createdAt'] ?? 0);
        });

        $this->global['pageTitle'] = 'StreamAdmin : Reports';
        $pageData = [
            'reports' => $reports,
        ];

        $this->loadViews('reports', $this->global, $pageData, NULL);
    }
    
    //users - redirect to User controller
     public function users()
    {
        redirect('Customer');
    }
      public function content()
    {
        redirect('content/content');
    }
       public function addcontent()
    {
        redirect('content/addPrioritizedVideo');
    }
           public function revenue()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
            return;
        }

        $startDateInput = trim((string)$this->input->get('start_date'));
        $endDateInput   = trim((string)$this->input->get('end_date'));

        $pageData = $this->prepareRevenueData($startDateInput, $endDateInput);
       

        $this->global['pageTitle'] = 'StreamAdmin : Revenue';
        $this->loadViews('revenue', $this->global, $pageData, NULL);
    }

    public function revenueByUser()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
            return;
        }

        $startDateInput = trim((string)$this->input->get('start_date'));
        $endDateInput   = trim((string)$this->input->get('end_date'));

        $pageData = $this->prepareRevenueDatabyUser($startDateInput, $endDateInput);

        $this->global['pageTitle'] = 'StreamAdmin : Revenue by User';
        $this->loadViews('revenue_by_user', $this->global, $pageData, NULL);
    }

    private function prepareRevenueDatabyUser($startDateInput, $endDateInput)
    {
        $today = new DateTime('today');
        $activeStart = (clone $today)->setTime(0, 0, 0);
        $activeEnd   = (clone $today)->setTime(23, 59, 59);

        $validCustomRange = false;
        if (!empty($startDateInput) && !empty($endDateInput)) {
            $start = DateTime::createFromFormat('Y-m-d', $startDateInput);
            $end   = DateTime::createFromFormat('Y-m-d', $endDateInput);
            if ($start && $end) {
                $start->setTime(0, 0, 0);
                $end->setTime(23, 59, 59);
                if ($start > $end) {
                    [$start, $end] = [$end, $start];
                }
                $activeStart = clone $start;
                $activeEnd   = clone $end;
                $validCustomRange = true;
            }
        }

        $activeStartMs = $activeStart->getTimestamp() * 1000;
        $activeEndMs   = $activeEnd->getTimestamp() * 1000;

        $transactionsRaw = $this->common->readdatafromcollectionwhereclause('AllTransactions');
        

        $transactions = [];
        $totalAmount = 0;
        $totalCoins = 0;
        $totalAdminShare = 0;
        $totalUserShare = 0;
        $hostBreakdown = [];
        $typeBreakdown = [];

        if (!empty($transactionsRaw) && is_array($transactionsRaw)) {
            foreach ($transactionsRaw as $id => $transaction) {
                if (!is_array($transaction)) {
                    continue;
                }

                $createdAtMs = isset($transaction['createdAtMs']) ? (int)$transaction['createdAtMs'] : null;
                if ($createdAtMs === null || ($createdAtMs < $activeStartMs && $createdAtMs > $activeEndMs)) {
                    continue;
                }
                if($transaction['type'] == 'coins'){
                    continue;
                }

                $amount = isset($transaction['totalEarning']) ? (float)$transaction['totalEarning'] : (isset($transaction['amount']) ? (float)$transaction['amount'] : 0.0);
                $coins  = isset($transaction['totalCoins']) ? (int)$transaction['totalCoins'] : 0;
                $adminShare = isset($transaction['adminShare']) ? (float)$transaction['adminShare'] : 0.0;
                $userShare  = isset($transaction['userShare']) ? (float)$transaction['userShare'] : 0.0;
                $hostIdRaw = isset($transaction['hostId']) ? trim((string)$transaction['hostId']) : '';
                $userIdRaw = isset($transaction['userId']) ? trim((string)$transaction['userId']) : '';
                $hostNameRaw = isset($transaction['hostName']) ? trim((string)$transaction['hostName']) : '';
                $hostName = $hostNameRaw !== '' ? $hostNameRaw : 'Unknown host';
                $resolvedHostId = $hostIdRaw !== '' ? $hostIdRaw : $userIdRaw;
                $hostKey = $resolvedHostId !== ''
                    ? 'id:' . strtolower($resolvedHostId)
                    : ($hostName !== '' ? 'name:' . strtolower($hostName) : 'unknown');
                $typeValue = $transaction['type'] ?? '';
                if (is_numeric($typeValue) || is_array($typeValue) || !is_string($typeValue)) {
                    $typeValue = '';
                }
                $typeValue = trim($typeValue);

                $transactions[] = [
                    'id'                 => $id,
                    'createdAtMs'        => $createdAtMs,
                    'amount'             => $amount,
                    'totalCoins'         => $coins,
                    'hostId'             => $hostId,
                    'hostName'           => $hostName,
                    'sessionId'          => $transaction['sessionId'] ?? '',
                    'walletTransactionId'=> $transaction['walletTransactionId'] ?? '',
                    'type'               => $typeValue,
                    'adminShare'         => $adminShare,
                    'userShare'          => $userShare,
                ];

                $totalAmount += $amount;
                $totalCoins  += $coins;
                $totalAdminShare += $adminShare;
                $totalUserShare  += $userShare;

                if (!isset($hostBreakdown[$hostKey])) {
                    $hostBreakdown[$hostKey] = [
                        'hostId'         => $resolvedHostId,
                        'hostName'       => $hostName,
                        'transactions'   => 0,
                        'totalAmount'    => 0.0,
                        'totalCoins'     => 0,
                        'totalAdminShare'=> 0.0,
                        'totalUserShare' => 0.0,
                        'lastTransaction'=> $createdAtMs,
                    ];
                } else {
                    if ($resolvedHostId !== '' && $hostBreakdown[$hostKey]['hostId'] === '') {
                        $hostBreakdown[$hostKey]['hostId'] = $resolvedHostId;
                    }
                    if ($hostBreakdown[$hostKey]['hostName'] === 'Unknown host' && $hostName !== 'Unknown host') {
                        $hostBreakdown[$hostKey]['hostName'] = $hostName;
                    }
                }

                $hostBreakdown[$hostKey]['transactions'] += 1;
                $hostBreakdown[$hostKey]['totalAmount'] += $amount;
                $hostBreakdown[$hostKey]['totalCoins'] += $coins;
                $hostBreakdown[$hostKey]['totalAdminShare'] += $adminShare;
                $hostBreakdown[$hostKey]['totalUserShare']  += $userShare;
                if ($createdAtMs > $hostBreakdown[$hostKey]['lastTransaction']) {
                    $hostBreakdown[$hostKey]['lastTransaction'] = $createdAtMs;
                }

                $typeKey = !empty($typeValue) ? $typeValue : 'Unknown';
                if (!isset($typeBreakdown[$typeKey])) {
                    $typeBreakdown[$typeKey] = [
                        'type'            => $typeKey,
                        'transactions'    => 0,
                        'totalAmount'     => 0.0,
                        'totalCoins'      => 0,
                        'totalAdminShare' => 0.0,
                        'totalUserShare'  => 0.0,
                    ];
                }
                $typeBreakdown[$typeKey]['transactions'] += 1;
                $typeBreakdown[$typeKey]['totalAmount'] += $amount;
                $typeBreakdown[$typeKey]['totalCoins']  += $coins;
                $typeBreakdown[$typeKey]['totalAdminShare'] += $adminShare;
                $typeBreakdown[$typeKey]['totalUserShare']  += $userShare;
            }
        }

        usort($transactions, static function ($a, $b) {
            return ($b['createdAtMs'] ?? 0) <=> ($a['createdAtMs'] ?? 0);
        });

        $hostBreakdown = array_map(function ($entry) {
            return [
                'hostId'         => $entry['hostId'],
                'hostName'       => $entry['hostName'],
                'transactions'   => $entry['transactions'],
                'totalAmount'    => $entry['totalAmount'],
                'totalCoins'     => $entry['totalCoins'],
                'totalAdminShare'=> $entry['totalAdminShare'],
                'totalUserShare' => $entry['totalUserShare'],
                'lastTransaction'=> $entry['lastTransaction'],
            ];
        }, array_values($hostBreakdown));
        usort($hostBreakdown, static function ($a, $b) {
            return ($b['totalAmount'] ?? 0) <=> ($a['totalAmount'] ?? 0);
        });

        $typeBreakdown = array_values($typeBreakdown);
        usort($typeBreakdown, static function ($a, $b) {
            return ($b['totalAmount'] ?? 0) <=> ($a['totalAmount'] ?? 0);
        });

        return [
            'transactions'     => $transactions,
            'totalAmount'      => $totalAmount,
            'totalCoins'       => $totalCoins,
            'transactionCount' => count($transactions),
            'hostBreakdown'    => $hostBreakdown,
            'totalAdminShare'  => $totalAdminShare,
            'totalUserShare'   => $totalUserShare,
            'typeBreakdown'    => $typeBreakdown,
            'filters'          => [
                'start_date' => $activeStart->format('Y-m-d'),
                'end_date'   => $activeEnd->format('Y-m-d'),
                'is_custom'  => $validCustomRange,
            ],
        ];
    }
    public function revenueBreakdown()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
            return;
        }

        try {
            $analyticsDoc = $this->common->readdatadocument('anylatics', 'totalrevenue');
            $analyticsSummary = is_array($analyticsDoc) ? $analyticsDoc : [];
        } catch (\Throwable $e) {
            $analyticsSummary = [];
        }

        $pageData['systemTotals'] = [
            'totalRevenue' => isset($analyticsSummary['totalrevenue']) ? (float)$analyticsSummary['totalrevenue'] : null,
            'adminShare'   => isset($analyticsSummary['adminshare']) ? (float)$analyticsSummary['adminshare'] : null,
            'userShare'    => isset($analyticsSummary['usershare']) ? (float)$analyticsSummary['usershare'] : null,
            'coinsEarned'  => isset($analyticsSummary['coins_erning']) ? (float)$analyticsSummary['coins_erning'] : null,
            'payable'      => isset($analyticsSummary['payable']) ? (float)$analyticsSummary['payable'] : null,
            'lastUpdated'  => isset($analyticsSummary['lastUpdatedAt']) ? (int)$analyticsSummary['lastUpdatedAt'] : null,
            'raw'          => $analyticsSummary,
        ];
      

        $this->global['pageTitle'] = 'StreamAdmin : Revenue Breakdown';
        $this->loadViews('revenue_breakdown', $this->global, [
            'systemTotals' => $pageData['systemTotals'],
        ], NULL);
    }

    public function revenueCoins()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
            return;
        }

        $startDateInput = trim((string)$this->input->get('start_date'));
        $endDateInput   = trim((string)$this->input->get('end_date'));

        $pageData = $this->prepareRevenueDatabyCoins($startDateInput, $endDateInput);

        $this->global['pageTitle'] = 'StreamAdmin : Revenue Coins';
        $this->loadViews('revenue_coins', $this->global, $pageData, NULL);
    }

    private function prepareRevenueDatabyCoins($startDateInput, $endDateInput)
    {
        $today = new DateTime('today');
        $activeStart = (clone $today)->setTime(0, 0, 0);
        $activeEnd   = (clone $today)->setTime(23, 59, 59);

        $validCustomRange = false;
        if (!empty($startDateInput) && !empty($endDateInput)) {
            $start = DateTime::createFromFormat('Y-m-d', $startDateInput);
            $end   = DateTime::createFromFormat('Y-m-d', $endDateInput);
            if ($start && $end) {
                $start->setTime(0, 0, 0);
                $end->setTime(23, 59, 59);
                if ($start > $end) {
                    [$start, $end] = [$end, $start];
                }
                $activeStart = clone $start;
                $activeEnd   = clone $end;
                $validCustomRange = true;
            }
        }

        $activeStartMs = $activeStart->getTimestamp() * 1000;
        $activeEndMs   = $activeEnd->getTimestamp() * 1000;

        $transactionsRaw = $this->common->readdatafromcollectionwhereclause('AllTransactions');
        

        $transactions = [];
        $totalAmount = 0;
        $totalCoins = 0;
        $totalAdminShare = 0;
        $totalUserShare = 0;
        $hostBreakdown = [];
        $typeBreakdown = [];

        if (!empty($transactionsRaw) && is_array($transactionsRaw)) {
            foreach ($transactionsRaw as $id => $transaction) {
                if (!is_array($transaction)) {
                    continue;
                }

                $createdAtMs = isset($transaction['createdAtMs']) ? (int)$transaction['createdAtMs'] : null;
                if ($createdAtMs === null || ($createdAtMs < $activeStartMs && $createdAtMs > $activeEndMs)) {
                    continue;
                }
                if($transaction['type'] == 'gifting'){
                    continue;
                }

                $amount = isset($transaction['totalEarning']) ? (float)$transaction['totalEarning'] : (isset($transaction['amount']) ? (float)$transaction['amount'] : 0.0);
                $coins  = isset($transaction['totalCoins']) ? (int)$transaction['totalCoins'] : 0;
                $adminShare = isset($transaction['adminShare']) ? (float)$transaction['adminShare'] : 0.0;
                $userShare  = isset($transaction['userShare']) ? (float)$transaction['userShare'] : 0.0;
                $hostIdRaw = isset($transaction['hostId']) ? trim((string)$transaction['hostId']) : '';
                $userIdRaw = isset($transaction['userId']) ? trim((string)$transaction['userId']) : '';
                $hostNameRaw = isset($transaction['hostName']) ? trim((string)$transaction['hostName']) : '';
                $hostName = $hostNameRaw !== '' ? $hostNameRaw : 'Unknown host';
                $resolvedHostId = $hostIdRaw !== '' ? $hostIdRaw : $userIdRaw;
                $hostKey = $resolvedHostId !== ''
                    ? 'id:' . strtolower($resolvedHostId)
                    : ($hostName !== '' ? 'name:' . strtolower($hostName) : 'unknown');
                $typeValue = $transaction['type'] ?? '';
                if (is_numeric($typeValue) || is_array($typeValue) || !is_string($typeValue)) {
                    $typeValue = '';
                }
                $typeValue = trim($typeValue);

                $transactions[] = [
                    'id'                 => $id,
                    'createdAtMs'        => $createdAtMs,
                    'amount'             => $amount,
                    'totalCoins'         => $coins,
                    'hostId'             => $hostId,
                    'hostName'           => $hostName,
                    'sessionId'          => $transaction['sessionId'] ?? '',
                    'walletTransactionId'=> $transaction['walletTransactionId'] ?? '',
                    'type'               => $typeValue,
                    'adminShare'         => $adminShare,
                    'userShare'          => $userShare,
                ];

                $totalAmount += $amount;
                $totalCoins  += $coins;
                $totalAdminShare += $adminShare;
                $totalUserShare  += $userShare;

                if (!isset($hostBreakdown[$hostKey])) {
                    $hostBreakdown[$hostKey] = [
                        'hostId'         => $resolvedHostId,
                        'hostName'       => $hostName,
                        'transactions'   => 0,
                        'totalAmount'    => 0.0,
                        'totalCoins'     => 0,
                        'totalAdminShare'=> 0.0,
                        'totalUserShare' => 0.0,
                        'lastTransaction'=> $createdAtMs,
                    ];
                } else {
                    if ($resolvedHostId !== '' && $hostBreakdown[$hostKey]['hostId'] === '') {
                        $hostBreakdown[$hostKey]['hostId'] = $resolvedHostId;
                    }
                    if ($hostBreakdown[$hostKey]['hostName'] === 'Unknown host' && $hostName !== 'Unknown host') {
                        $hostBreakdown[$hostKey]['hostName'] = $hostName;
                    }
                }

                $hostBreakdown[$hostKey]['transactions'] += 1;
                $hostBreakdown[$hostKey]['totalAmount'] += $amount;
                $hostBreakdown[$hostKey]['totalCoins'] += $coins;
                $hostBreakdown[$hostKey]['totalAdminShare'] += $adminShare;
                $hostBreakdown[$hostKey]['totalUserShare']  += $userShare;
                if ($createdAtMs > $hostBreakdown[$hostKey]['lastTransaction']) {
                    $hostBreakdown[$hostKey]['lastTransaction'] = $createdAtMs;
                }

                $typeKey = !empty($typeValue) ? $typeValue : 'Unknown';
                if (!isset($typeBreakdown[$typeKey])) {
                    $typeBreakdown[$typeKey] = [
                        'type'            => $typeKey,
                        'transactions'    => 0,
                        'totalAmount'     => 0.0,
                        'totalCoins'      => 0,
                        'totalAdminShare' => 0.0,
                        'totalUserShare'  => 0.0,
                    ];
                }
                $typeBreakdown[$typeKey]['transactions'] += 1;
                $typeBreakdown[$typeKey]['totalAmount'] += $amount;
                $typeBreakdown[$typeKey]['totalCoins']  += $coins;
                $typeBreakdown[$typeKey]['totalAdminShare'] += $adminShare;
                $typeBreakdown[$typeKey]['totalUserShare']  += $userShare;
            }
        }

        usort($transactions, static function ($a, $b) {
            return ($b['createdAtMs'] ?? 0) <=> ($a['createdAtMs'] ?? 0);
        });

        $hostBreakdown = array_map(function ($entry) {
            return [
                'hostId'         => $entry['hostId'],
                'hostName'       => $entry['hostName'],
                'transactions'   => $entry['transactions'],
                'totalAmount'    => $entry['totalAmount'],
                'totalCoins'     => $entry['totalCoins'],
                'totalAdminShare'=> $entry['totalAdminShare'],
                'totalUserShare' => $entry['totalUserShare'],
                'lastTransaction'=> $entry['lastTransaction'],
            ];
        }, array_values($hostBreakdown));
        usort($hostBreakdown, static function ($a, $b) {
            return ($b['totalAmount'] ?? 0) <=> ($a['totalAmount'] ?? 0);
        });

        $typeBreakdown = array_values($typeBreakdown);
        usort($typeBreakdown, static function ($a, $b) {
            return ($b['totalAmount'] ?? 0) <=> ($a['totalAmount'] ?? 0);
        });

        return [
            'transactions'     => $transactions,
            'totalAmount'      => $totalAmount,
            'totalCoins'       => $totalCoins,
            'transactionCount' => count($transactions),
            'hostBreakdown'    => $hostBreakdown,
            'totalAdminShare'  => $totalAdminShare,
            'totalUserShare'   => $totalUserShare,
            'typeBreakdown'    => $typeBreakdown,
            'filters'          => [
                'start_date' => $activeStart->format('Y-m-d'),
                'end_date'   => $activeEnd->format('Y-m-d'),
                'is_custom'  => $validCustomRange,
            ],
        ];
    }
    private function prepareRevenueData($startDateInput, $endDateInput)
    {
        $today = new DateTime('today');
        $activeStart = (clone $today)->setTime(0, 0, 0);
        $activeEnd   = (clone $today)->setTime(23, 59, 59);

        $validCustomRange = false;
        if (!empty($startDateInput) && !empty($endDateInput)) {
            $start = DateTime::createFromFormat('Y-m-d', $startDateInput);
            $end   = DateTime::createFromFormat('Y-m-d', $endDateInput);
            if ($start && $end) {
                $start->setTime(0, 0, 0);
                $end->setTime(23, 59, 59);
                if ($start > $end) {
                    [$start, $end] = [$end, $start];
                }
                $activeStart = clone $start;
                $activeEnd   = clone $end;
                $validCustomRange = true;
            }
        }

        $activeStartMs = $activeStart->getTimestamp() * 1000;
        $activeEndMs   = $activeEnd->getTimestamp() * 1000;

        $transactionsRaw = $this->common->readdatafromcollectionwhereclause('AllTransactions');
        

        $transactions = [];
        $totalAmount = 0;
        $totalCoins = 0;
        $totalAdminShare = 0;
        $totalUserShare = 0;
        $hostBreakdown = [];
        $typeBreakdown = [];

        if (!empty($transactionsRaw) && is_array($transactionsRaw)) {
            foreach ($transactionsRaw as $id => $transaction) {
                if (!is_array($transaction)) {
                    continue;
                }

                $createdAtMs = isset($transaction['createdAtMs']) ? (int)$transaction['createdAtMs'] : null;
                if ($createdAtMs === null || ($createdAtMs < $activeStartMs && $createdAtMs > $activeEndMs)) {
                    continue;
                }

                $amount = isset($transaction['totalEarning']) ? (float)$transaction['totalEarning'] : (isset($transaction['amount']) ? (float)$transaction['amount'] : 0.0);
                $coins  = isset($transaction['totalCoins']) ? (int)$transaction['totalCoins'] : 0;
                $adminShare = isset($transaction['adminShare']) ? (float)$transaction['adminShare'] : 0.0;
                $userShare  = isset($transaction['userShare']) ? (float)$transaction['userShare'] : 0.0;
                $hostId = isset($transaction['hostId']) ? (string)$transaction['hostId'] : 'unknown';
                $hostName = isset($transaction['hostName']) ? (string)$transaction['hostName'] : 'Unknown host';
                $typeValue = $transaction['type'] ?? '';
                if (is_numeric($typeValue) || is_array($typeValue) || !is_string($typeValue)) {
                    $typeValue = '';
                }
                $typeValue = trim($typeValue);

                $transactions[] = [
                    'id'                 => $id,
                    'createdAtMs'        => $createdAtMs,
                    'amount'             => $amount,
                    'totalCoins'         => $coins,
                    'hostId'             => $hostId,
                    'hostName'           => $hostName,
                    'sessionId'          => $transaction['sessionId'] ?? '',
                    'walletTransactionId'=> $transaction['walletTransactionId'] ?? '',
                    'type'               => $typeValue,
                    'adminShare'         => $adminShare,
                    'userShare'          => $userShare,
                ];
            

                $totalAmount += $amount;
                $totalCoins  += $coins;
                $totalAdminShare += $adminShare;
                $totalUserShare  += $userShare;

                if (!isset($hostBreakdown[$hostId])) {
                    $hostBreakdown[$hostId] = [
                        'hostId'         => $hostId,
                        'hostName'       => $hostName,
                        'transactions'   => 0,
                        'totalAmount'    => 0.0,
                        'totalCoins'     => 0,
                        'totalAdminShare'=> 0.0,
                        'totalUserShare' => 0.0,
                        'lastTransaction'=> $createdAtMs,
                    ];
                }

                $hostBreakdown[$hostId]['transactions'] += 1;
                $hostBreakdown[$hostId]['totalAmount'] += $amount;
                $hostBreakdown[$hostId]['totalCoins'] += $coins;
                $hostBreakdown[$hostId]['totalAdminShare'] += $adminShare;
                $hostBreakdown[$hostId]['totalUserShare']  += $userShare;
                if ($createdAtMs > $hostBreakdown[$hostId]['lastTransaction']) {
                    $hostBreakdown[$hostId]['lastTransaction'] = $createdAtMs;
                }

                $typeKey = !empty($typeValue) ? $typeValue : 'Unknown';
                if (!isset($typeBreakdown[$typeKey])) {
                    $typeBreakdown[$typeKey] = [
                        'type'            => $typeKey,
                        'transactions'    => 0,
                        'totalAmount'     => 0.0,
                        'totalCoins'      => 0,
                        'totalAdminShare' => 0.0,
                        'totalUserShare'  => 0.0,
                    ];
                }
                $typeBreakdown[$typeKey]['transactions'] += 1;
                $typeBreakdown[$typeKey]['totalAmount'] += $amount;
                $typeBreakdown[$typeKey]['totalCoins']  += $coins;
                $typeBreakdown[$typeKey]['totalAdminShare'] += $adminShare;
                $typeBreakdown[$typeKey]['totalUserShare']  += $userShare;
            }
        }

        usort($transactions, static function ($a, $b) {
            return ($b['createdAtMs'] ?? 0) <=> ($a['createdAtMs'] ?? 0);
        });

        $hostBreakdown = array_values($hostBreakdown);
        usort($hostBreakdown, static function ($a, $b) {
            return ($b['totalAmount'] ?? 0) <=> ($a['totalAmount'] ?? 0);
        });

        $typeBreakdown = array_values($typeBreakdown);
        usort($typeBreakdown, static function ($a, $b) {
            return ($b['totalAmount'] ?? 0) <=> ($a['totalAmount'] ?? 0);
        });

        return [
            'transactions'     => $transactions,
            'totalAmount'      => $totalAmount,
            'totalCoins'       => $totalCoins,
            'transactionCount' => count($transactions),
            'hostBreakdown'    => $hostBreakdown,
            'totalAdminShare'  => $totalAdminShare,
            'totalUserShare'   => $totalUserShare,
            'typeBreakdown'    => $typeBreakdown,
            'filters'          => [
                'start_date' => $activeStart->format('Y-m-d'),
                'end_date'   => $activeEnd->format('Y-m-d'),
                'is_custom'  => $validCustomRange,
            ],
        ];
    }
            public function gifts()
    {
        redirect('gifts');
    }
           public function transactions()
    {
        // Redirect to Transaction controller
        redirect('transaction');
    }
             public function announcement()
    {
        redirect('announcement/announcements');
    }
           public function tick()
    {
        redirect('tick/requests');
    }
           public function role()
    {
        redirect('role/roles');
    }
    
    // Redirect to admin management
    public function adminusers()
    {
        redirect('admin/admins');
    }
      public function promotion()
    {
        //  $data['users']=$this->common->readdatafromcollectionwhereclause('Users');
        // $this->loadViews('users',$data);
              $this->loadViews('promotion');
    }
    //vehicle
     public function vehicle()
    {
        $data['vehicles']=$this->common->readdatafromcollectionwhereclause('Vehicles');
        // echo "<pre>";
        // print_r($data['vehicles']);
        // echo "</pre>";
        // exit;
        $this->loadViews('vehicle',$data);
    }
    //vendors
     public function vendors()
    {
        $this->loadViews('vendors');
    }
    //viewapprovres
     public function viewapprovres()
    {
        $this->loadViews('viewapprovres');
    }
    //viewbanned
     public function viewbanned($id="")
    {
        $data['id']=$id;
        $data['banned']=$this->common->readdatadocument('BannedPeople',$id);
        $this->loadViews('viewbanned',$data);
    }
    public function unbanned($id="")
    {
        $this->common->updatedatamodel('BannedPeople',$id,['status'=>'unbanned']);
        $this->session->set_flashdata('success', 'Banned person unbanned successfully');
        redirect(base_url('site/bannedpeople'));
    }
    public function banned($id="")
    {
        $this->common->updatedatamodel('BannedPeople',$id,['status'=>'banned']);
        $this->session->set_flashdata('success', 'Banned person banned successfully');
        redirect(base_url('site/bannedpeople'));
    }
    //viewent
     public function viewent($id="")
    {
        if($id==""){
            redirect(base_url('site/entandext'));
        }
        $data['id']=$id;
        $data['entrance']=$this->common->readdatadocument('AuthorizationEntries',$id);
        $this->loadViews('viewent',$data);
    }
    //viewhistory
         public function viewhistory()
    {
        $this->loadViews('viewhistory');
    }
    //viewmessage
             public function viewmessage($id="")
    {
        if($id==""){
            redirect(base_url('site/allsentmessage'));
        }
        $data['id']=$id;
        $data['message']=$this->common->readdatadocument('Messages',$id);
        $this->loadViews('viewmessage',$data);
    }
    //copytemplate
    public function copytemplate($id="")
    {
        $data['id']=$id;
        $data['message']=$this->common->readdatadocument('Messages',$id);
        $data['users']=$this->common->readdatafromcollectionwhereclause('Users');
        $this->loadViews('copytemplate',$data);
    }
    //viewreservation
                 public function viewreservation($id="")
    {
        if($id==""){
            redirect(base_url('site/reservations'));
        }
       $data['reservationId']=$id;
        $data['reservation']=$this->common->readdatadocument('Reservations',$id);
        if($data['reservation']['eventId']){
            $data['amenity']=$this->common->readdatadocument('Ammenities',$data['reservation']['eventId']);
        }else{
            $data['amenity']=array();
        }
        $this->loadViews('viewreservation',$data);
    }

    

    public function submitApprovReason()
    {
        $data=$this->input->post();
        $J['admin_review_title']=$data['approved_title'];
        $J['admin_review_reason']=$data['approvedReason'];
        $J['reservationStatus']="approved";
        $J['admin_review_date']=time()*1000;
        $this->common->updatedatamodel('Reservations',$data['reservationId'],$J);

        $this->session->set_flashdata('success', 'Reservation approved successfully');
        redirect(base_url('site/approvedreservations'));
    }
    public function submitDenyReason()
    {
        $data=$this->input->post();
        $J['admin_review_title']=$data['deny_title'];
        $J['admin_review_reason']=$data['denyReason'];
        $J['reservationStatus']="rejected";
        $J['admin_review_date']=time()*1000;
        $this->common->updatedatamodel('Reservations',$data['reservationId'],$J);

        $this->session->set_flashdata('success', 'Reservation approved successfully');
        redirect(base_url('site/reservations'));

    }
    public function issuereported()
    {
        $this->loadViews('issuereported');
    }
    //viewwarning
    public function viewwarning($id="")
    {
        if($id==""){
            redirect(base_url('site/warnings'));
        }
        $data['warningId']=$id;
        $data['warning']=$this->common->readdatadocument('Warnings',$id);
        $data['occurrences']=$this->common->nextedreaddatafromcollectionwhereclause('Warnings',$id,"Occurrences");
        // echo "<pre>";
        // print_r($data);
        // echo "</pre>";
        // exit;
 
        $this->loadViews('viewwarning',$data);
    }
    //warnings
    public function warnings()
    {
        if (!$this->isAdmin()) {
            $this->loadThis();
            return;
        }

        $warnedUsersRaw = $this->common->readdatafromcollectionwhereclause('Users', 'status', '==', 'warning');
        $warnedUsersRaw = is_array($warnedUsersRaw) ? $warnedUsersRaw : [];

        $warnedUsers = [];
        foreach ($warnedUsersRaw as $userId => $userData) {
            if (!is_array($userData)) {
                continue;
            }

            $warningCount = isset($userData['warningCount']) ? (int)$userData['warningCount'] : 0;
            $lastWarningAt = isset($userData['lastWarningAt']) ? (int)$userData['lastWarningAt'] : null;
            $fullName = isset($userData['fullName']) && $userData['fullName'] !== '' ? $userData['fullName'] : ($userData['name'] ?? '');
            $email = isset($userData['email']) ? $userData['email'] : '';

            $warnedUsers[] = [
                'id'            => $userId,
                'fullName'      => $fullName !== '' ? $fullName : 'Unknown user',
                'email'         => $email,
                'warningCount'  => $warningCount,
                'lastWarningAt' => $lastWarningAt,
                'status'        => isset($userData['status']) ? $userData['status'] : 'warning',
            ];
        }

        usort($warnedUsers, static function ($a, $b) {
            return ($b['lastWarningAt'] ?? 0) <=> ($a['lastWarningAt'] ?? 0);
        });

        $pageData = [
            'warnedUsers'   => $warnedUsers,
            'warnedCount'   => count($warnedUsers),
        ];

        $this->global['pageTitle'] = 'StreamAdmin : Warned Users';
        $this->loadViews('warnings', $this->global, $pageData, NULL);
    }
    
    public function suspendWarnedUser()
    {
        if (!$this->isAdmin() || !$this->input->is_ajax_request()) {
            show_404();
            return;
        }

        $userId = trim($this->input->post('userId'));
        if (empty($userId)) {
            $this->jsonError('Invalid user id');
            return;
        }

        $user = $this->common->readdatadocument('Users', $userId);
        if (empty($user)) {
            $this->jsonError('User not found');
            return;
        }

        try {
            $this->permanentlySuspendUser($userId, 'Suspended via warnings panel', 'warnpanel_' . substr($userId, -6));
        } catch (\Throwable $e) {
            log_message('error', 'Failed to suspend user ' . $userId . ': ' . $e->getMessage());
            $this->jsonError('Could not suspend user');
            return;
        }

        $nowMs = time() * 1000;
        $this->common->updatedatamodel('Users', $userId, [
            'status'         => 'suspend',
            'lastSuspendedAt'=> $nowMs,
        ]);

        $this->jsonSuccess([
            'userId' => $userId,
            'status' => 'suspend',
        ]);
    }

    //waterratess
    public function waterrates()
    {
        $data['waterRates']=$this->common->readdatafromcollectionwhereclause('WaterRates');
        $this->loadViews('waterrates',$data);
    }
    public function parking()
    {
        $this->loadViews('parking');
    }

    public function event()
    {
        $this->loadViews('event');
    }

    public function viewevent()
    {
        $this->loadViews('viewevent');
    }

    public function addevent()
    {
        $this->loadViews('addevent');
    }

    public function settings()
    {
        $this->loadViews('settings');
    }

    public function help()
    {
        $this->loadViews('help');
    }

    public function profile()
    {
         $user = $this->session->userdata('session_data');
         
         if (empty($user)) {
             redirect(base_url('login'));
         }
         
         $data['userinfo'] = $this->common->readdatadocument('Admin', $user['userId']);
         $data['userId'] = $user['userId'];
         
         $this->global['pageTitle'] = 'StreamAdmin : My Profile';
         $this->loadViews('profile', $this->global, $data, NULL);
    }
    public function updateprofile()
    {
        $userId = $this->input->post('userId');
        
        if (empty($userId)) {
            $this->session->set_flashdata('error', 'Invalid user');
            redirect(base_url('site/profile'));
            return;
        }

        // Validate inputs
        $this->form_validation->set_rules('fullName', 'Full Name', 'trim|required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('phone', 'Phone', 'trim|required');

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

        $updateData = array(
            'fullName' => $this->input->post('fullName'),
            'email' => $this->input->post('email'),
            'phone' => $this->input->post('phone')
        );

        // Handle profile image upload
        if (!empty($_FILES['profileImage']['tmp_name'])) {
            try {
                $firebase = $this->firebase->init();
                $storage = $firebase->createStorage();
                $defaultBucket = $storage->getBucket();

                $uploadedFile = $defaultBucket->upload(
                    file_get_contents($_FILES['profileImage']['tmp_name']),
                    [
                        'name' => "admin/profiles/" . time() . "_" . $_FILES['profileImage']['name']
                    ]
                );

                $updateData['profileImage'] = $uploadedFile->info()['mediaLink'];
            } catch (Exception $e) {
                $this->session->set_flashdata('error', 'Failed to upload image: ' . $e->getMessage());
                redirect(base_url('site/profile'));
                return;
            }
        }

        // Update in Firebase
        try {
            $this->common->updatedatamodel('Admin', $userId, $updateData);
            
            // Update session data
            $session_data = $this->session->userdata('session_data');
            $session_data['name'] = $updateData['fullName'];
            if (isset($updateData['profileImage'])) {
                $session_data['profileImage'] = $updateData['profileImage'];
            }
            $this->session->set_userdata('session_data', $session_data);
            
            $this->session->set_flashdata('success', 'Profile updated successfully');
        } catch (Exception $e) {
            $this->session->set_flashdata('error', 'Failed to update profile: ' . $e->getMessage());
        }
        
        redirect(base_url('site/profile'));
    }

    /**
     * Change Password
     */
    public function changePassword()
    {
        $userId = $this->input->post('userId');
        
        if (empty($userId)) {
            echo json_encode(array('status' => false, 'message' => 'Invalid user'));
            return;
        }

        $newPassword = $this->input->post('newPassword');
        $confirmPassword = $this->input->post('confirmPassword');

        // Validate inputs
        if (empty($newPassword) || empty($confirmPassword)) {
            echo json_encode(array('status' => false, 'message' => 'All fields are required'));
            return;
        }

        if ($newPassword !== $confirmPassword) {
            echo json_encode(array('status' => false, 'message' => 'New password and confirm password do not match'));
            return;
        }

        if (strlen($newPassword) < 6) {
            echo json_encode(array('status' => false, 'message' => 'Password must be at least 6 characters long'));
            return;
        }

        try {
            // Get user data
            $userData = $this->common->readdatadocument('Admin', $userId);
            
            if (empty($userData)) {
                echo json_encode(array('status' => false, 'message' => 'User not found'));
                return;
            }

            // Update password in Firebase Auth
            $firebase = $this->firebase->init();
            $auth = $firebase->createAuth();
            
            try {
                $auth->changeUserPassword($userId, $newPassword);
                
                // Also update hashed password in Admin collection
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                $this->common->updatedatamodel('Admin', $userId, array('password' => $newPassword));
                
                echo json_encode(array('status' => true, 'message' => 'Password changed successfully'));
            } catch (Exception $e) {
                echo json_encode(array('status' => false, 'message' => 'Failed to change password: ' . $e->getMessage()));
            }
        } catch (Exception $e) {
            echo json_encode(array('status' => false, 'message' => 'Error: ' . $e->getMessage()));
        }
    }

    public function password()
    {
        $this->loadViews('password');
    }
    public function addAmmenityData()
    {
        $firebase = $this->firebase->init();
		$storage = $firebase->createStorage();
		$defaultBucket = $storage->getBucket();

        $data=$this->input->post();
        if(isset($data['paymentRequired']) && $data['paymentRequired']=="on"){
            $data['paymentRequired']=true;
        }else{
            $data['paymentRequired']=false;
        }
        if(isset($data['capacityLimit']) && $data['capacityLimit']=="on"){
            $data['capacityLimit']=true;
        }else{
            $data['capacityLimit']=false;
        }
        if(isset($data['approvalRequired']) && $data['approvalRequired']=="on"){
            $data['approvalRequired']=true;
        }else{
            $data['approvalRequired']=false;
        }
        /*
        if ($_FILES['termsFile']['tmp_name'] != '') {
			$uploadedFile = $defaultBucket->upload(
				file_get_contents($_FILES['termsFile']['tmp_name']),
				[
					'name' => "termsFile" . rand() . time() . $_FILES['termsFile']['name'],
				]
			);

			$data["termsFile"] = $uploadedFile->info()['mediaLink'];
		}else{
			$data["termsFile"] = "";
		}
        */
        $data['startDateMs']=strtotime($data['startDate'])*1000;
        $data['endDateMs']=strtotime($data['endDate'])*1000;
        if($data['calendarType']=="hourly" || $data['calendarType']=="once_day"){
        $x=array();
        $openTime12h = date("g A", strtotime($data['openTime']));
        $closeTime12h = date("g A", strtotime($data['closeTime']));
        //array_push($x,$openTime12h);
        //array_push($x,$closeTime12h);
        $x[$openTime12h."-".$closeTime12h]="available";
        $data['timeforapp']=$x;
        }
       else if($data['calendarType']=="day_night"){
            $x=array();
            $openTime12h = date("g A", strtotime($data['dayOpen']));
            $closeTime12h = date("g A", strtotime($data['dayClose']));
            $x[$openTime12h."-".$closeTime12h]="available";
            $openTime12h = date("g A", strtotime($data['nightOpen']));
            $closeTime12h = date("g A", strtotime($data['nightClose']));
            $x[$openTime12h."-".$closeTime12h]="available";



            $data['timeforapp']=$x;
            }
        else if($data['calendarType']=="custom_slots"){
            $x=array();
            for($i=0;$i<count($data['fromTime']);$i++){
                $fromTime= date("g A", strtotime($data['fromTime'][$i]));
                $toTime= date("g A", strtotime($data['toTime'][$i]));
                $x[$fromTime."-".$toTime]="available";

            }
            $data['timeforapp']=$x;
            
         }

         if($data['selectedImage']==""){
            $data['imageUrl']=$data['defaultImage'];
         }else{
            $data['imageUrl']=$data['selectedImage'];
         }
         $data['createdAt']=time()*1000;
         $data['updatedAt']=time()*1000;
         $data['limitPerDay']=intval($data['limitPerDay']);
         $data['limitPerWeek']=intval($data['limitPerWeek']);
         $data['maxPeople']=intval($data['maxPeople']);
         $data['price']=intval($data['price']);
         $data['status']="active";
         $key=time().rand().time();
         $data['id']=$key;
         $this->common->adddatamodel('Ammenities',$key,$data);
         redirect(base_url('site/amenities'));
       
        
    }

    public function updateAmmenityData($id)
    {
        $firebase = $this->firebase->init();
        $storage = $firebase->createStorage();
        $defaultBucket = $storage->getBucket();

        $data = $this->input->post();
        
        // Handle checkboxes
        $data['paymentRequired'] = isset($data['paymentRequired']) && $data['paymentRequired'] == "on";
        $data['capacityLimit'] = isset($data['capacityLimit']) && $data['capacityLimit'] == "on";
        $data['approvalRequired'] = isset($data['approvalRequired']) && $data['approvalRequired'] == "on";

        // Handle dates
        $data['startDateMs'] = strtotime($data['startDate']) * 1000;
        $data['endDateMs'] = strtotime($data['endDate']) * 1000;

        // Handle time slots based on calendar type
        if($data['calendarType'] == "hourly" || $data['calendarType'] == "once_day") {
            $x = array();
            $openTime12h = date("g A", strtotime($data['openTime']));
            $closeTime12h = date("g A", strtotime($data['closeTime']));
            $x[$openTime12h."-".$closeTime12h] = "available";
            $data['timeforapp'] = $x;
        }
        else if($data['calendarType'] == "day_night") {
            $x = array();
            $openTime12h = date("g A", strtotime($data['dayOpen']));
            $closeTime12h = date("g A", strtotime($data['dayClose']));
            $x[$openTime12h."-".$closeTime12h] = "available";
            $openTime12h = date("g A", strtotime($data['nightOpen']));
            $closeTime12h = date("g A", strtotime($data['nightClose']));
            $x[$openTime12h."-".$closeTime12h] = "available";
            $data['timeforapp'] = $x;
        }
        else if($data['calendarType'] == "custom_slots") {
            $x = array();
            for($i = 0; $i < count($data['fromTime']); $i++) {
                $fromTime = date("g A", strtotime($data['fromTime'][$i]));
                $toTime = date("g A", strtotime($data['toTime'][$i]));
                $x[$fromTime."-".$toTime] = "available";
            }
            $data['timeforapp'] = $x;
        }

        // Handle image
        if($data['selectedImage'] == "") {
            $data['imageUrl'] = $data['defaultImage'];
        } else {
            $data['imageUrl'] = $data['selectedImage'];
        }

        // Handle numeric values
        $data['limitPerDay'] = intval($data['limitPerDay']);
        $data['limitPerWeek'] = intval($data['limitPerWeek']);
        $data['maxPeople'] = intval($data['maxPeople']);
        $data['price'] = intval($data['price']);
        
        // Update timestamp
        $data['updatedAt'] = time() * 1000;

        // Update the amenity
        $result = $this->common->updatedatamodel('Ammenities', $id, $data);
        
        if($result) {
            $this->session->set_flashdata('success', 'Amenity updated successfully');
        } else {
            $this->session->set_flashdata('error', 'Failed to update amenity');
        }
        
        redirect('site/amenities');
    }

    public function fetchReplies()
    {
         $issueId ="dcUZWhUUXMnPk7sVNLIh"; 
        
        //$this->input->post('issueId');
        $lastTimestamp = 1717219200000;
        //$this->input->post('lastTimestamp');

        try {
            // Get replies from Firebase
            $replies =$this->common->readnextcollection('Issues',$issueId,"Conversations");
           
            // Filter replies newer than lastTimestamp
            $newReplies = array_filter($replies, function($reply) use ($lastTimestamp) {
                return $reply['createdAt'] > $lastTimestamp;
            });
            // echo "<pre>";
            // var_dump($newReplies);
            // echo "</pre>";
            // exit;

            echo json_encode([
                'success' => true,
                'replies' => array_values($newReplies)
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }

    public function sendReply()
    {
        $issueId = $this->input->post('issueId');
        $replyText = $this->input->post('replyText');
        $userId = $this->input->post('userId');
        
        try {
            $firebase = $this->firebase->init();
            $storage = $firebase->createStorage();
            $defaultBucket = $storage->getBucket();

            $reply = [
                'note' => $replyText,
                'fromId' =>"Admin",
                'toId' =>$userId ,
                'createdAt' => time()*1000,
            ];

            // Handle file upload if present
            if (!empty($_FILES['replyFile']['tmp_name'])) {
                $uploadedFile = $defaultBucket->upload(
                    file_get_contents($_FILES['replyFile']['tmp_name']),
                    [
                        'name' => "issues/$issueId/replies/" . time() . "_" . $_FILES['replyFile']['name']
                    ]
                );
                $reply['attachmentUrl'] = $uploadedFile->info()['mediaLink'];
                $reply['attachmentName'] = $_FILES['replyFile']['name'];
            }

            // Add reply to Firebase
            $replyId = time() . rand();
            $this->common->addnextcollection('Issues', $issueId, 'Conversations', $replyId, $reply);

            echo json_encode([
                'success' => true,
                'reply' => $reply
            ]);
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }

    public function addreservationsdata()
    {
        $data = $this->input->post();
        date_default_timezone_set('UTC');

        $date = $this->input->post('date');
        $inputDateMs = strtotime(date('Y-m-d 00:00:00', strtotime($date))) * 1000;
        $amenityId = $this->input->post('amenity');
            
        if (!$date || !$amenityId) {
            echo json_encode([
                'success' => false,
                'message' => 'Date and amenity ID are required'
            ]);
            exit;
        }
        $amenity = $this->common->readdatadocument('Ammenities', $amenityId);
        $unit=$this->common->readdatadocument('units',$this->input->post('units'));
        $userId="";
        if($unit['owner']!=""){
            $userId=$unit['owner'];
        }else{
            $userId=$unit['tenant'];
        }
        
        if (!$amenity) {
            echo json_encode([
                'success' => false,
                'message' => 'Amenity not found'
            ]);
            exit;
            return;
        }
        if ($userId =="") {
            echo json_encode([
                'success' => false,
                'message' => 'User not found'
            ]);
            exit;
            return;
        }

        $timeLabel = $this->input->post('slot');
        $key = "{$inputDateMs}_{$timeLabel}";
        if(!isset($amenity['completionTimeForApp'][$key])){
            //echo "yes";
            $personCount = $amenity['timePersonCount'][$key] ?? 0;
            $maxPeople = $amenity['maxPeople'] ?? 0;
             $currentCount = $personCount + $this->input->post('number_of_people');    
            if($currentCount > $maxPeople){ 
                echo json_encode([
                    'success' => false,
                    'message' => 'People has been reached'
                ]);
                exit;
            }
            else{

               if($currentCount===$maxPeople){
                $up['completionTimeForApp'][$key]="booked";
                $amenity['completionTimeForApp'][$key]="booked";
                $up['timePersonCount'][$key]=$currentCount;
                $amenity['timePersonCount'][$key]=$currentCount;
               }else{
                $up['completionTimeForApp'][$key]="available";
                $amenity['completionTimeForApp'][$key]="available";
                $up['timePersonCount'][$key]=$currentCount;
                $amenity['timePersonCount'][$key]=$currentCount;
               }
               
               $alltimeslot=$amenity['timeforapp'];
               $bookedstatus = 'booked'; // default to booked

                foreach ($alltimeslot as $key => $value) {
                    $newkey = "{$inputDateMs}_{$key}";
                    
                    if (!isset($amenity['completionTimeForApp'][$newkey]) || $amenity['completionTimeForApp'][$newkey] != "booked") {
                        $bookedstatus = "available";
                        break; // exit loop immediately when any available slot is found
                    }
                }
                if($bookedstatus=="booked"){
                $up['calenderBookingStatus'][$inputDateMs]="booked";
                }else{
                $up['calenderBookingStatus'][$inputDateMs]="available";
                }
                $this->common->updatedatamodel('Ammenities',$amenityId,$up);

                $reservationId=time().rand();
                $res['id']=$reservationId;
                $res['note']=$this->input->post('note');
                $res['reservedSlot']=$this->input->post('slot');
                $res['numberOfPersons']=(int)$this->input->post('number_of_people');
                $res['bookingStatus']="paid";
                $res['isApproved']=true;
                $res['reservationStatus']="approved";
                $res['eventId']=$amenityId;
                $res['createdAt']=time()*1000;
                $res['eventDate']=$inputDateMs;
                $res['eventImageUrl']=$amenity['imageUrl'];
                $res['eventName']=$amenity['name'];
                $res['unitId']=$this->input->post('units');
                $res['userId']=$userId;
                $data['createdAt']=time()*1000;
                $this->common->adddatamodel('Reservations',$reservationId,$res);
                echo json_encode([
                    'success' => true,
                    'input'=>$this->input->post(),
                    'reservation'=>$res,
                    'up'=>$up,
                    'message' => 'People has added'
                ]);
                exit;
            }


        }
        else{

            $personCount = $amenity['timePersonCount'][$key] ?? 0;
            $maxPeople = $amenity['maxPeople'] ?? 0;
             $currentCount = $personCount + (int)$this->input->post('number_of_people');   
             if($currentCount > $maxPeople){ 
                echo json_encode([
                    'success' => false,
                    'message' => 'People has been reached'
                ]);
                exit;
            }
            else{

               if($currentCount===$maxPeople){
                $up['completionTimeForApp'][$key]="booked";
                $amenity['completionTimeForApp'][$key]="booked";
                $up['timePersonCount'][$key]=$currentCount;
                $amenity['timePersonCount'][$key]=$currentCount;
               }else{
                $up['completionTimeForApp'][$key]="available";
                $amenity['completionTimeForApp'][$key]="available";
                $up['timePersonCount'][$key]=$currentCount;
                $amenity['timePersonCount'][$key]=$currentCount;
               }
               
               $alltimeslot=$amenity['timeforapp'];
               $bookedstatus = 'booked'; // default to booked

                foreach ($alltimeslot as $key => $value) {
                    $newkey = "{$inputDateMs}_{$key}";
                    
                    if (!isset($amenity['completionTimeForApp'][$newkey]) || $amenity['completionTimeForApp'][$newkey] != "booked") {
                        $bookedstatus = "available";
                        break; // exit loop immediately when any available slot is found
                    }
                }
                if($bookedstatus=="booked"){
                $up['calenderBookingStatus'][$inputDateMs]="booked";
                }else{
                $up['calenderBookingStatus'][$inputDateMs]="available";
                }
                $this->common->updatedatamodel('Ammenities',$amenityId,$up);

                $reservationId=time().rand();
                $res['id']=$reservationId;
                $res['note']=$this->input->post('note');
                $res['reservedSlot']=$this->input->post('slot');
                $res['numberOfPersons']=(int)$this->input->post('number_of_people');
                $res['bookingStatus']="paid";
                $res['isApproved']=true;
                $res['eventId']=$amenityId;
                $res['createdAt']=time()*1000;
                $res['eventDate']=$inputDateMs;
                $res['eventImageUrl']=$amenity['imageUrl'];
                $res['eventName']=$amenity['name'];
                $res['unitId']=$this->input->post('units');
                $res['userId']=$userId;
                $res['reservationStatus']="approved";
                $this->common->adddatamodel('Reservations',$reservationId,$res);


                $data['createdAt']=time()*1000;
                echo json_encode([
                    'success' => false,
                    'input'=>$this->input->post(),
                    'reservation'=>$res,
                    'up'=>$up,
                    'message' => 'People has added'
                ]);
                exit;
            }

        }
        

        echo "<pre>";
        print_r($amenity);
        echo "<br>";
        print_r($key);
        echo "</pre>";
        exit;
        

    }


    public function getAvailableSlots() {
        try {
            date_default_timezone_set('UTC');

            $date = $this->input->post('date');
            
            // Convert to midnight time and get milliseconds
            $inputDateMs = strtotime(date('Y-m-d 00:00:00', strtotime($date))) * 1000;
      //      echo  $date = date('Y-m-d H:i:s', strtotime($date1));
        //    echo "<br>";
          //  echo strtotime($date)*1000;
            //exit;

            $amenityId = $this->input->post('amenityId');
            
            if (!$date || !$amenityId) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Date and amenity ID are required'
                ]);
                exit;
            }

            // Get amenity details
            $amenity = $this->common->readdatadocument('Ammenities', $amenityId);
            
            if (!$amenity) {
                echo json_encode([
                    'success' => false,
                    'message' => 'Amenity not found'
                ]);
                exit;
                return;
            }
            $availableSlots = [];
            if ($inputDateMs >= $amenity['startDateMs'] && $inputDateMs <= $amenity['endDateMs']) {
                $inputDateMs = strtotime($date . ' 00:00:00') * 1000;
                $timeSlots = $amenity['timeforapp'] ?? [];
                foreach ($timeSlots as  $timeLabel => $status) {
                  $key = "{$inputDateMs}_{$timeLabel}";
                //    echo "<br>";
                if(isset($amenity['completionTimeForApp'][$key])){
                   // $timeSlots = $amenity['timeforapp'] ?? [];
                  //  $bookedSlots = $amenity['bookedSlots'] ?? [];
                    $currentcount=0;
                    
                    $slotStatus = $amenity['completionTimeForApp'][$key] ?? 'available';
                    $personCount = $amenity['timePersonCount'][$key] ?? 0;
                    if($slotStatus =="available"){
                        $availableSlots[] = [
                            'time' => $timeLabel,
                        ];
                    }


                }else{
                    $availableSlots[] = [
                        'time' => $timeLabel,
                    ];
                }



                   /*
                     if($slotStatus =="available"){
                        $resevercount=3;
                        $currentcount=$resevercount+$personCount;
                        if($amenity['maxPeople']>=$currentcount){
                            if($personCount < $resevercount){
                                $availableSlots[] = [
                                    'time' => $timeLabel,
                                ];
                            }
                            
                        }
                        
                        else{
                            echo json_encode([
                                'success' => false,
                                'message' => 'People has been reached'
                            ]);
                            exit;

                        } 
                             
                    
                    }
                        */

/*
                    if ($slotStatus === 'booked') {
                        echo json_encode([
                            'success' => false,
                            'message' => 'No Slot has been found'
                        ]);
                        exit;
                    }
                        */
                }
                     

                    
                
                echo json_encode([
                    'success' => true,

                    'slots' => $availableSlots
                ]);
                exit;

            }else{
                echo json_encode([
                    'success' => false,
                    'message' => 'Amenity is not available for this date'
                ]);
                exit;
            }


           

        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }
    }

    public function solvewarning($warningId) {
        try {
            if (!$warningId) {
                $this->session->set_flashdata('error', 'Warning ID is required');
                redirect('site/warnings');
                return;
            }

            // Get the warning
            $warning = $this->common->readdatadocument('Warnings', $warningId);
            
            if (!$warning) {
                $this->session->set_flashdata('error', 'Warning not found');
                redirect('site/warnings');
                return;
            }

            // Update warning status
            $updateData = [
                'status' => 'solved',
                'solvedAt' => time() * 1000,
 
            ];

            $result = $this->common->updatedatamodel('Warnings', $warningId, $updateData);

            if ($result) {
                $this->session->set_flashdata('success', 'Warning marked as solved successfully');
            } else {
                $this->session->set_flashdata('error', 'Failed to solve warning');
            }

        } catch (Exception $e) {
            $this->session->set_flashdata('error', 'An error occurred: ' . $e->getMessage());
        }

        redirect('site/warnings');
    }

    public function emailtemplates()
    {
        $data['templates'] = $this->common->readdatafromcollectionwhereclause('EmailTemplates');
        $this->loadViews('emailtemplates', $data);
    }

    public function addtemplate()
    {
        $this->loadViews('addtemplate');
    }

    public function savetemplate()
    {
        try {
            $data = $this->input->post();
            
            // Add additional fields
            $data['id'] = time() . rand();
            $data['createdAt'] = time() * 1000;
            $data['updatedAt'] = time() * 1000;
            
            // Save to Firebase
            $this->common->adddatamodel('EmailTemplates', $data['id'], $data);
            
            $this->session->set_flashdata('success', 'Email template created successfully');
            redirect(base_url('site/messagecenter'));
        } catch (Exception $e) {
            $this->session->set_flashdata('error', 'Failed to create template: ' . $e->getMessage());
            redirect(base_url('site/addtemplate'));
        }
    }

    public function edittemplate($id = "")
    {
        if ($id == "") {
            redirect(base_url('site/emailtemplates'));
        }
        
        $data['templateId'] = $id;
        $data['template'] = $this->common->readdatadocument('EmailTemplates', $id);
        
        if (!$data['template']) {
            $this->session->set_flashdata('error', 'Template not found');
            redirect(base_url('site/emailtemplates'));
        }
        
        $this->loadViews('addtemplate', $data);
    }

    public function updatetemplate($id = "")
    {
        if ($id == "") {
            redirect(base_url('site/emailtemplates'));
        }

        try {
            $data = $this->input->post();
            $data['updatedAt'] = time() * 1000;
            
            $this->common->updatedatamodel('EmailTemplates', $id, $data);
            
            $this->session->set_flashdata('success', 'Email template updated successfully');
            redirect(base_url('site/emailtemplates'));
        } catch (Exception $e) {
            $this->session->set_flashdata('error', 'Failed to update template: ' . $e->getMessage());
            redirect(base_url('site/edittemplate/' . $id));
        }
    }

    public function deletetemplate($id = "")
    {
        if ($id == "") {
            redirect(base_url('site/emailtemplates'));
        }

        try {
            $this->common->deletedatamodel('EmailTemplates', $id);
            $this->session->set_flashdata('success', 'Email template deleted successfully');
        } catch (Exception $e) {
            $this->session->set_flashdata('error', 'Failed to delete template: ' . $e->getMessage());
        }
        
        redirect(base_url('site/emailtemplates'));
    }

    private function _processMessageData($data, $type ,$messageId="") {
        if($messageId==""){
            $messageId = time() . rand();
        }
        $attachments = [];

        // Handle file uploads
        if (!empty($_FILES['attachments']['name'])) {
            $firebase = $this->firebase->init();
            $storage = $firebase->createStorage();
            $defaultBucket = $storage->getBucket();

            // Convert single file upload to array format
            $files = [];
            if (!is_array($_FILES['attachments']['name'])) {
                foreach ($_FILES['attachments'] as $key => $value) {
                    $files[$key] = [$value];
                }
                $_FILES['attachments'] = $files;
            }

            foreach ($_FILES['attachments']['tmp_name'] as $key => $tmp_name) {
                if (!empty($tmp_name)) {
                    $file_name = $_FILES['attachments']['name'][$key];
                    $uploadedFile = $defaultBucket->upload(
                        file_get_contents($tmp_name),
                        [
                            'name' => "messages/{$messageId}/attachments/" . time() . "_" . $file_name
                        ]
                    );
                    $attachments[] = [
                        'name' => $file_name,
                        'url' => $uploadedFile->info()['mediaLink']
                    ];
                }
            }
        }

        // Process recipients
        $recipients = explode(',', $data['selected_recipients']);
        $recipientsList = [];
        foreach ($recipients as $recipient) {
            list($recipientType, $value) = explode('-', $recipient);
            $recipientsList[] = [
                'type' => $recipientType,
                'value' => $value
            ];
        }

        // Build recipientuserlistid array
        $recipientuserlistid = [];
        $units = $this->common->readdatafromcollectionwhereclause('units');
        foreach ($recipients as $recipient) {
            if ($recipient === 'list-all_units') {
                // Get all cohosts from all units
                foreach ($units as $unit) {
                    if (!empty($unit['cohost']) && is_array($unit['cohost'])) {
                        foreach ($unit['cohost'] as $cohostId) {
                            if (!empty($cohostId)) {
                                $recipientuserlistid[] = $cohostId;
                            }
                        }
                    }
                    if (!empty($unit['owner'])) {
                        $recipientuserlistid[] = $unit['owner'];
                    }
                    if (!empty($unit['tenant'])) {
                        $recipientuserlistid[] = $unit['tenant'];
                    }



                }
            } elseif ($recipient === 'list-owners') {
                // Get all owners from all units
                foreach ($units as $unit) {
                    if (!empty($unit['owner'])) {
                        $recipientuserlistid[] = $unit['owner'];
                    }
                }
            } elseif (strpos($recipient, 'user-') === 0) {
                // Get user ID from user-xxxx
                $parts = explode('-', $recipient, 2);
                if (isset($parts[1]) && !empty($parts[1])) {
                    $recipientuserlistid[] = $parts[1];
                }
            }
        }
        $jana=array();
        $recipientuserlistid = array_unique($recipientuserlistid);
        foreach($recipientuserlistid as $user){
            $jana[$user]=false;
        }

        
        
        // Prepare message data
        $messageData = [
            'id' => $messageId,
            'template_id' => $data['template_id'] ?? "",

            'subject' => $data['subject'],
            'content' => $data['content'],
            'recipients' => $recipientsList,
            'recipientuserlistid' => $jana,
            'attachments' => $attachments,
            'send_copy' => isset($data['send_copy']) ? true : false,
            'send_time' => $data['send_time'],
            'status' => $type === 'draft' ? 'draft' : 'pending',
            'createdAt' => time() * 1000,
            'updatedAt' => time() * 1000,
            'createdBy' => $this->session->userdata('userId')
        ];

        // Add scheduled time if specified
        if ($data['send_time'] === 'specificDate') {
            $messageData['scheduled_time'] = strtotime($data['scheduled_time']) * 1000;
        }

        return $messageData;
    }

    public function savedraft() {
        try {
            $data = $this->input->post();
            $messageData = $this->_processMessageData($data, 'draft');
            // echo "<pre>";
            // print_r($messageData);
            // echo "</pre>";
            // exit;
            // // Save to Firebase
            $this->common->adddatamodel('Messages', $messageData['id'], $messageData);
            
            $this->session->set_flashdata('success', 'Message saved as draft successfully');
            
        } catch (Exception $e) {
            $this->session->set_flashdata('error', 'Failed to save draft: ' . $e->getMessage());
        }
        
        redirect(base_url('site/messagecenter'));
    }

    public function sendmessage() {
        try {
            $data = $this->input->post();
           
            $messageData = $this->_processMessageData($data, 'send');
          
            
            // Save to Firebase
            $this->common->adddatamodel('Messages', $messageData['id'], $messageData);
            
            // If immediate sending
            if ($data['send_time'] === 'immediately') {
                // Here you would typically trigger your message sending mechanism
                // For example, calling a background job or email service
                
                // Update status to sent
                $messageData['status'] = 'sent';
                $messageData['sentAt'] = time() * 1000;
                $this->common->updatedatamodel('Messages', $messageData['id'], $messageData);
                
                $this->session->set_flashdata('success', 'Message sent successfully');
            } else {
                
                    $data['status']="scheduled";
                    $data['scheduled_time']=strtotime($data['scheduled_time'])*1000;
                    $this->common->updatedatamodel('Messages', $messageData['id'], $messageData);
                


                $this->session->set_flashdata('success', 'Message scheduled for sending');
            }
            
        } catch (Exception $e) {
            $this->session->set_flashdata('error', 'Failed to send message: ' . $e->getMessage());
        }
        
        redirect(base_url('site/messagecenter'));
    }

    public function addchecklist() {
        // Get all POST data
        $data = $this->input->post();
        
        // Initialize the structured data
        $structuredData = array();
        
        // Get areas and instructions
        $areas = isset($data['area']) ? $data['area'] : array();
        $instructions = isset($data['instruction']) ? $data['instruction'] : array();
        
        // Calculate how many instructions per area
        $instructionsPerArea = array();
        
        // Get the area indices from the form data
        $areaIndices = isset($data['area_index']) ? $data['area_index'] : array();
        
        // Group instructions by area index
        if (isset($data['instruction']) && is_array($data['instruction'])) {
            foreach ($data['instruction'] as $index => $instruction) {
                if (!empty($instruction)) {
                    // Get the area index for this instruction
                    $areaIndex = isset($areaIndices[$index]) ? $areaIndices[$index] : 0;
                    
                    if (!isset($instructionsPerArea[$areaIndex])) {
                        $instructionsPerArea[$areaIndex] = array();
                    }
                    $instructionsPerArea[$areaIndex][] = $instruction;
                }
            }
        }
        
        
        // Build the structured data
        $areaToCheck = array();
        
        foreach ($areas as $areaIndex => $areaName) {
            if (!empty($areaName)) {
                $areaData = array(
                    'areaName' => $areaName,
                    'areaToCheck' => array()
                );
                
                // Add instructions for this area
                if (isset($instructionsPerArea[$areaIndex])) {
                    foreach ($instructionsPerArea[$areaIndex] as $instruction) {
                        if (!empty($instruction)) {
                            $areaData['areaToCheck'][$instruction] = false; // Default to false
                        }
                    }
                }
                
                $areaToCheck[] = $areaData;
            }
        }
        
        // Create the final structured data
        $finalData = array(
            'areaToCheck' => $areaToCheck,
            'createdAt' => time() * 1000,
            'endDate' => isset($data['finish_date']) ? strtotime($data['finish_date']) * 1000 : null,
            'frequency' => isset($data['frequency']) ? ucfirst($data['frequency']) : '',
            'from_hour' => isset($data['from_hour']) ? $data['from_hour'] : '',
            'to_hour' => isset($data['to_hour']) ? $data['to_hour'] : '',
            'progress' => 0,
            'startDate' => isset($data['start_date']) ? strtotime($data['start_date']) * 1000 : null,
            'title' => isset($data['title']) ? $data['title'] : ''
        );
        
        if (!empty($_FILES['file']['tmp_name'])) {
            $uploadedFile = $defaultBucket->upload(
                file_get_contents($_FILES['file']['tmp_name']),
                [
                    'name' => "issues/$issueId/replies/" . time() . "_" . $_FILES['file']['name']
                ]
            );
            $finalData['imageUrl'] = $uploadedFile->info()['mediaLink'];
            $finalData['imageName'] = $_FILES['file']['name'];
        }else{
            $finalData['imageUrl'] = '';
            $finalData['imageName'] = '';
        }
        $id=time().rand();
        $finalData['id']=$id;
        $this->common->adddatamodel('CheckLists', $id, $finalData);
        $this->session->set_flashdata('success', 'Checklist created successfully');
        redirect(base_url('site/checklists'));
    }

    public function reportSendWarning()
    {
        // if (!$this->isAdmin() || !$this->input->is_ajax_request()) {
        //     show_404();
        //     return;
        // }

        $reportId = trim($this->input->post('reportId'));
        if (empty($reportId)) {
            $this->jsonError('Invalid report id');
            return;
        }

        $report = $this->common->readdatadocument('Reports', $reportId);
        if (empty($report)) {
            $this->jsonError('Report not found');
            return;
        }

        $userId = $this->extractReportedUserId($report);
        if (empty($userId)) {
            $this->jsonError('Reported user not found');
            return;
        }

        $user = $this->common->readdatadocument('Users', $userId);
        $warningCount = isset($user['warningCount']) ? (int)$user['warningCount'] : 0;
        $warningCount++;
        $nowMs = time() * 1000;

        $historyId = 'warn_' . time() . '_' . substr($reportId, -6);
        $historyData = [
            'id'          => $historyId,
            'userId'      => $userId,
            'reportId'    => $reportId,
            'reason'      => $report['reason'] ?? '',
            'note'        => $report['note'] ?? '',
            'handledBy'   => $this->currentAdminId(),
            'createdAt'   => $nowMs,
            'warningCount'=> $warningCount,
            'status'      => $warningCount >= 3 ? 'suspend' : 'warning',
        ];
        $this->common->adddatamodel('WarningHistory', $historyId, $historyData);

        $userStatus = $warningCount >= 3 ? 'suspend' : 'warning';

        $userUpdate = [
            'warningCount' => $warningCount,
            'lastWarningAt'=> $nowMs,
            'status'       => $userStatus,
        ];

        $permanentBlocked = false;

        if ($warningCount >= 3) {
            $this->permanentlySuspendUser($userId, 'Permanent suspension: reached 3 warnings', $reportId);
            $permanentBlocked = true;
        } else {
            $this->suspendUserForHours($userId, 1, 'Temporary suspension after warning', $reportId);
        }

        $this->common->updatedatamodel('Users', $userId, $userUpdate);

        $this->common->updatedatamodel('Reports', $reportId, [
            'actionTaken'   => true,
            'actionType'    => 'warning',
            'actionTakenAt' => $nowMs,
            'handledBy'     => $this->currentAdminId(),
        ]);

        $this->jsonSuccess([
            'warningCount'  => $warningCount,
            'status'        => $userStatus,
            'permanentBlocked' => $permanentBlocked,
        ]);
    }

    public function reportSuspend()
    {
        if (!$this->isAdmin() || !$this->input->is_ajax_request()) {
            show_404();
            return;
        }

        $reportId = trim($this->input->post('reportId'));
        if (empty($reportId)) {
            $this->jsonError('Invalid report id');
            return;
        }

        $report = $this->common->readdatadocument('Reports', $reportId);
        if (empty($report)) {
            $this->jsonError('Report not found');
            return;
        }

        $userId = $this->extractReportedUserId($report);
        if (empty($userId)) {
            $this->jsonError('Reported user not found');
            return;
        }

        $this->permanentlySuspendUser($userId, 'Manual permanent suspension from report', $reportId);

        $nowMs = time() * 1000;
        $this->common->updatedatamodel('Reports', $reportId, [
            'actionTaken'   => true,
            'actionType'    => 'permanent_suspend',
            'actionTakenAt' => $nowMs,
            'handledBy'     => $this->currentAdminId(),
        ]);

        $this->jsonSuccess([
            'status'            => 'suspend',
            'permanentBlocked'  => true,
        ]);
    }

    public function reportDelete()
    {
        if (!$this->isAdmin() || !$this->input->is_ajax_request()) {
            show_404();
            return;
        }

        $reportId = trim($this->input->post('reportId'));
        if (empty($reportId)) {
            $this->jsonError('Invalid report id');
            return;
        }

        try {
            $this->common->deletedatamodel('Reports', $reportId);
            $this->jsonSuccess();
        } catch (\Exception $e) {
            $this->jsonError($e->getMessage());
        }
    }

    private function extractReportedUserId(array $report): string
    {
        if (!empty($report['reported'])) {
            return $report['reported'];
        }

        if (!empty($report['reportedUser']) && is_array($report['reportedUser']) && !empty($report['reportedUser']['id'])) {
            return $report['reportedUser']['id'];
        }

        return '';
    }

    private function currentAdminId(): string
    {
        $session = $this->session->userdata('session_data');
        return $session['userId'] ?? ($session['id'] ?? '');
    }

    private function suspendUserForHours(string $userId, int $hours, string $reason, string $reportId): void
    {
        // $firebase = $this->firebase->init();
        // $auth = $firebase->createAuth();
        // $auth->disableUser($userId);

        $nowMs = time() * 1000;
        $endsAt = $nowMs + ($hours * 60 * 60 * 1000);

        $this->common->updatedatamodel('Users', $userId, [
            'approved'       => false,
            'suspendedUntil' => $endsAt,
            'lastSuspendedAt'=> $nowMs,
        ]);

        $historyId = 'suspend_' . time() . '_' . substr($reportId, -6);
        $historyData = [
            'id'            => $historyId,
            'userId'        => $userId,
            'reportId'      => $reportId,
            'reason'        => $reason,
            'durationHours' => $hours,
            'handledBy'     => $this->currentAdminId(),
            'createdAt'     => $nowMs,
        ];
        $this->common->adddatamodel('SuspensionHistory', $historyId, $historyData);
    }

    private function permanentlySuspendUser(string $userId, string $reason, string $reportId): void
    {
        $firebase = $this->firebase->init();
        $auth = $firebase->createAuth();
        $auth->disableUser($userId);

        $nowMs = time() * 1000;

        $this->common->updatedatamodel('Users', $userId, [
            'approved'       => false,
            'suspendedUntil' => null,
            'lastSuspendedAt'=> $nowMs,
            'status'         => 'suspend',
        ]);

        $historyId = 'suspend_' . time() . '_' . substr($reportId, -6);
        $historyData = [
            'id'            => $historyId,
            'userId'        => $userId,
            'reportId'      => $reportId,
            'reason'        => $reason,
            'durationHours' => null,
            'handledBy'     => $this->currentAdminId(),
            'createdAt'     => $nowMs,
            'isPermanent'   => true,
            'action'        => 'suspend',
        ];
        $this->common->adddatamodel('SuspensionHistory', $historyId, $historyData);
    }

    private function jsonSuccess(array $extra = [])
    {
        $payload = array_merge(['success' => true], $extra);
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($payload));
    }

    private function jsonError(string $message)
    {
        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode(['success' => false, 'message' => $message]));
    }

}
