<?php

class Members extends CI_Model
{
     function __construct()
     {
          $this->proTable   = 'products';
     }

     public function getAllUsers($limit = false)
     {
          if ($limit) {
               $this->db->limit($limit);
          }
          $this->db->order_by("id", "desc");
          $this->db->where('role', 2);
          $query = $this->db->get('users');
          return $query->result_array();
     }


     function get_user_all_fund_requests($id)
     {
          return $this->db->order_by("id", "desc")->get_where('fund_request', array('user_id' => $id))->result_array();
     }

     function get_user_all_package_history($id)
     {
          return $this->db->order_by("id", "desc")->get_where('subscription', array('user_id' => $id))->result_array();
     }



     function getParentByUserId($id)
     {
          $getUserFromLog = $this->db->get_where('user_logs', array('user_id' => $id))->row_array();
          // var_dump($getUserFromLog); die;
          if ($getUserFromLog) {
               $getUserFromUsrTable = $this->db->get_where('users', array('id' => $getUserFromLog['referral_id']))->row_array();
               if ($getUserFromUsrTable) {
                    return $getUserFromUsrTable;
               }
          }
          return false;
     }





     function get_users()
     {

          $this->db->join('memberships', 'memberships.user_id = user_logs.user_id', 'left');
          $query = $this->db->get('user_logs');
          $result = $query->result_array();
          return $result ? $result : false;
     }




     function get_member_earning($id)
     {
          $data = $this->db->get_where('member_earnings', array('user_id' => $id))->row_array();
          return $data ? $data["amount"] : false;
     }


     function getPackageFromId($id)
     {
          $package = $this->db->get_where('products', array('id' => $id))->row_array();
          return $package ? $package : false;
     }



     function add_user_log($userId, $parentId)
     {
          $data = array();
          $data["user_id"] = $userId;
          $data["referral_id"] = $parentId;
          $data["created_at"] = Helpers::date();
          $response = $this->db->insert('user_logs', $data);
          return $response ? $response : false;
     }
     function checkIfUserBoughtSubscription($userId, $packageId)
     {

          $this->db->where('user_id', $userId);
          $this->db->where('package_id', $packageId);
          $query = $this->db->get('memberships');
          $data =  $query->row_array();
          return $data ? $data : false;
     }

     function checkIfUserIsQualified($userId, $packageId)
     {
          $this->db->where('sponsor_id', $userId);
          $this->db->where('package_id', $packageId);
          $query = $this->db->get('transactions');
          return $query->row_array();
     }

     function checkUserHigherQualifiedPackage($userId)
     {
          $this->db->order_by("id", "desc");
          $this->db->select_max('package_id');
          $this->db->where('sponsor_id', $userId);
          $query = $this->db->get('transactions');
          return $query->row_array();
     }

     function makeUserQualified($userId)
     {
          $data = array(
               'isQualified' => 1
          );
          $this->db->where('id', $userId);
          $this->db->update('users', $data);
          if ($this->db->affected_rows()) {
               return true;
          } else {
               return false;
          }
     }

     function add_transaction($data)
     {
          $response = $this->db->insert('transaction', $data);
          return $response;
     }
     function add_membership_to_user_account($userId, $packageId)
     {


          $data = array();
          $data["user_id"] = $userId;
          $data["package_id"] = $packageId;
          $data["purchase_date"] = Helpers::date();
          $response = $this->db->insert('memberships', $data);
          return $response ? $response : false;
     }

     function add_support_ticket($data)
     {
          $response = $this->db->insert('support', $data);
          return $response ? $response : false;
     }

     function load_package_content($id)
     {
          $package = $this->db->get_where('contents', array('package_id' => $id))->row_array();
          return $package ? $package : false;
     }


     function get_members_higher_package($userId)
     {
          $this->db->where('user_id', $userId);
          $this->db->order_by("id", "desc");
          $query = $this->db->get('memberships');
          $data = $query->row_array();
          return $data ? $data : false;
     }


     function get_user_all_packages($userId)
     {
          $this->db->where('user_id', $userId);
          $this->db->order_by("id", "Asc");
          $query = $this->db->get('memberships');
          $data = $query->result_array();
          return $data ? $data : false;
     }

     function get_members_higher_subscription($userId)
     {
          $this->db->where('user_id', $userId);
          $this->db->order_by("id", "desc");
          $this->db->select_max('package_id');
          $query = $this->db->get('subscription');
          $data = $query->row_array();
          if ($data['package_id']) {
               return $this->db->get_where('subscription', array('package_id' => $data['package_id'], "user_id" => $userId))->row_array();
          }
          return false;
     }
     function is_user_qualified($userId)
     {
          $package = $this->db->get_where('transactions', array('sponsor_id' => $userId))->row_array();
          return $package ? $package : false;
     }

     function add_selected_membership($data)
     {
          $response = $this->db->insert('memberships', $data);
          return $response ? $response : false;
     }

     function store_fund($data)
     {
          $this->db->insert('fund_request', $data);
          return $this->db->insert_id();
     }



     function get_user_support_message($id)
     {
          $this->db->order_by("id", "desc");

          $data = $this->db->where("user_id", $id)->get('support')->result_array();

          return $data ? $data : false;
     }

     function add_earning_amount($userId, $data)
     {
          $user = $this->get_user_earning($userId);
          if ($user) {
               $response = $this->db->query("UPDATE ewallet SET amount = amount + {$data["amount"]} WHERE id = {$user['id']}");
               //$response = $query->result_array();
          } else {
               $response = $this->db->insert('ewallet', $data);
          }
          return $response;
     }

     function get_user_earning($id)
     {
          $data = $this->db->get_where('ewallet', array('user_id' => $id))->row_array();
          return $data ? $data : false;
     }

     function substract_earning_amount($userId, $amount)
     {
          $user = $this->get_user_earning($userId);
          $response = false;

          if ($user) {
               $response = $this->db->query("UPDATE ewallet SET amount = amount - {$amount} WHERE user_id = {$userId}");
          }
          return $response;
     }



     function get_user_all_earnings($id)
     {
          $data = $this->db->get_where('ewallet', array('user_id' => $id))->result_array();
          return $data ? $data : false;
     }



     function get_team_from_packId($userId, $packId = false)
     {
          $this->db->or_where(array('sponsor_id' => $userId, 'to_id' => $userId));
          if ($packId) {
               $this->db->where('package_id', $packId);
          }
          $query = $this->db->get('transactions');
          $result = $query->result_array();
          return $result ? $result : false;
     }

     function getMyTeam($userId)
     {
          $this->db->where("user_logs.referral_id", $userId);
          $this->db->join('users as u', 'user_logs.user_id = u.id', 'left');
          $query = $this->db->get('user_logs');
          $result = $query->result_array();
          return $result ? $result : false;
     }

     function getUserEarningByCoinType($userId, $type = false)
     {
          $data = $this->db->get_where('member_earnings', array('user_id' => $userId))->row_array();
          return $data ? $data : false;
     }



     function add_withraw_request($data)
     {
          $response = $this->db->insert('withdraw_request', $data);
          return $response ? $response : false;
     }
     function get_user_last_transaction($id)
     {
          return $this->db->order_by("id", "desc")->get_where('fund_request', array('user_id' => $id))->row_array();
     }

     function get_single_transaction($id)
     {
          return $this->db->get_where('fund_request', array('transection_id' => $id))->row_array();
     }

     function get_user_last_transaction_by_coin($id, $wallet_type)
     {
          return $this->db->order_by("id", "desc")->get_where('fund_request', array('user_id' => $id, 'wallet_type' => $wallet_type))->row_array();
     }

     function find_a_transaction($user_id, $packageId)
     {
          $package = $this->db->get_where('transactions', array('sponsor_id' => $user_id, 'package_id' => $packageId))->row_array();
          return $package ? $package : false;
     }

     function find_transactions_for_user_reports($user_id)
     {
          $transactions = $this->db->get_where('transactions', array('to_id' => $user_id))->result_array();
          return $transactions ? $transactions : false;
     }

     function find_referral_transactions($user_id, $packageId)
     {
          $package = $this->db->get_where('transactions', array('from_id' => $user_id, 'package_id' => $packageId))->result_array();
          return $package ? $package : false;
     }
     function add_commission_email($userId, $packId)
     {
          $data = array();
          $data["user_id"] = $userId;
          $data["pack_id"] = $packId;
          $data["status"] = 0;
          $data["created_at"] = Helpers::date();

          $response = $this->db->insert('commission_email', $data);
          return $response ? $response : false;
     }

     function getAllThePendingCronEmails()
     {
          $data = $this->db->get('commission_email')->result_array();
          return $data ? $data : false;
     }

     function deleteCommissionEmailsData($data)
     {
          if (!empty($data)) {
               $this->db->where_in('id', $data);
               $this->db->delete('commission_email');
               if ($this->db->affected_rows()) {
                    return true;
               } else {
                    return false;
               }
          }
     }

     function store_cron($data)
     {
          $response = $this->db->insert('cron_status', $data);
          return $response;
     }

     function saveDataToSubscription($data)
     {
          if ($this->db->insert('subscription', $data)) {
               $id = $this->db->insert_id();
               $sub = $this->db->get_where('subscription', array('id' => $id))->row_array();
               return $sub;
          }
          return false;
     }

     function getSubscriptionByPK($id)
     {
          $sub = $this->db->get_where('subscription', array('id' => $id))->row_array();
          return $sub;
     }

     function getSubscriptionByPackageId($id, $packId)
     {
          $sub = $this->db->get_where('subscription', array('user_id' => $id, 'package_id' => $packId))->row_array();
          return $sub;
     }


     function getAllSubscriptions()
     {
          $subscription = $this->db->get_where('subscription', ['level' => 0])->result_array();
          return $subscription ? $subscription : false;
     }

     function getAllLevelCommissionSubscriptions()
     {
          $subscription = $this->db->get_where('subscription', ['level >' => 0])->result_array();
          return $subscription ? $subscription : false;
     }

     function get_user_last_roi_transaction($id)
     {
          return $this->db->order_by("id", "desc")->get_where('roi', array('subscription_id' => $id))->row_array();
     }

     function get_user_all_roi_transaction_by_subscription_id($id)
     {
          return $this->db->order_by("id", "desc")->get_where('roi', array('subscription_id' => $id, 'user_id !=' => 1))->result_array();
     }

     function get_user_roi_transaction($id, $order = true)
     {
          if ($order) {
               $this->db->order_by("id", "desc");
          }
          return $this->db->get_where('roi', array('user_id' => $id))->result_array();
     }

     function get_user_distrinct_roi_transaction($id)
     {
          $sql = "SELECT * FROM roi where id in (SELECT max(id) FROM roi WHERE user_id = {$id} GROUP BY subscription_id )";
          // 		$this->db->group_by('subscription_id');
          // 		$this->db->order_by("id", "desc");
          return $this->commonRawQuery($sql);
     }

     // function getROIsFromSubscription() {}
     function get_user_all_subscription($id, $order = true)
     {
          if ($order) {
               $this->db->order_by("id", "desc");
          }
          return $this->db->get_where('subscription', array('user_id' => $id))->result_array();
     }
     function saveCronResult($count = false, $message = false)
     {
          $message = $message ? $message : "ROI given to " . $count . " users";
          $data['status'] = $message;
          $data['created_at'] = Helpers::date();
          $response = $this->db->insert('cron_status', $data);
          return $response;
     }

     function saveRoiTransaction($data)
     {
          $res = $this->db->insert("roi", $data);
          return $res ? $res : false;
     }

     function SaveCommissionToDB($data)
     {
          $res = $this->db->insert("commission", $data);
          return $res ? $res : false;
     }

     function saveUserToDirectory($data)
     {
          $res = $this->db->insert("directory", $data);
          return $res ? $res : false;
     }

     function EditUserDirectory($id, $data)
     {
          $this->db->where('id', $id)->update("directory", $data);
          if ($this->db->affected_rows()) {
               return true;
          } else {
               return false;
          }
     }

     function searchDirectoryByTag($tag)
     {
          $this->db->like('tags', $tag);
          $query = $this->db->get('directory');
          $result = $query->result_array();
          return $result ? $result : false;
     }
     function getUserDirectory($userId)
     {
          return $this->db->get_where('directory', array('user_id' => $userId))->row_array();
     }

     function getUserDirectoryByPk($id)
     {
          return $this->db->get_where('directory', array('id' => $id))->row_array();
     }

     function get_user_all_commissions($userId)
     {
          return $this->db->order_by("commission.id", "desc")->join('users', 'users.id = commission.from_id', 'left')->get_where('commission', array('user_id' => $userId))->result_array();
     }

     function get_user_all_withdraw_requests($userId)
     {
          return $this->db->order_by("id", "desc")->get_where('withdraw_request', array('user_id' => $userId))->result_array();
     }

     function get_user_all_approved_withdraw_requests($userId)
     {
          return $this->db->order_by("id", "desc")->get_where('withdraw_request', array('user_id' => $userId, 'status' => 1))->result_array();
     }

     function getDirectoryData()
     {
          return $this->db->order_by("id", "desc")->get("directory")->result_array();
     }

     function resetEarnings($id)
     {
          $response = $this->db->query("UPDATE member_earnings SET amount = 0 WHERE id = {$id}");
          return $response;
     }

     function commonRawQuery($sql)
     {
          $query = $this->db->query($sql);
          return $query->result_array();
     }

     function getAdminROIOfUser($subIds)
     {
          if (!empty($subIds)) {
               $this->db->where_in('subscription_id', $subIds);
               $this->db->where('user_id', 1);
               $query = $this->db->get('roi');
               $getUsers = $query->result_array();
               if ($getUsers) {
                    return $getUsers;
               } else {
                    return false;
               }
          }
     }

     function getLevelUserInfo($ids)
     {
          if (!empty($ids)) {
               $this->db->select('users.*, memberships.package_id, u.referral_id, v.username as parent');
               $this->db->where_in('users.id', $ids);
               $this->db->join('memberships', 'memberships.user_id = users.id', 'left');
               $this->db->join('user_logs as u', 'u.user_id = users.id', 'left');
               $this->db->join('users as v', 'u.referral_id = v.id', 'left');
               $query = $this->db->get('users');
               $getUsers = $query->result_array();
               if ($getUsers) {
                    return $getUsers;
               } else {
                    return false;
               }
          }
     }

     function getEpinFromCode($epin)
     {
          $package = $this->db->get_where('epin', array('epin' => $epin, 'status' => 0))->row_array();
          return $package ? $package : false;
     }
     function getEpinByPk($id)
     {
          $package = $this->db->get_where('epin', array('id' => $id))->row_array();
          return $package ? $package : false;
     }



     function add_fund_transfer($data)
     {
          $response = $this->db->insert('wallet_funds_transfer', $data);
          return $response ? $response : false;
     }

     function getUserFundTransfer($userID)
     {
          $this->db->where(array('user_id' => $userID));
          $this->db->join('users', 'users.id = wallet_funds_transfer.to_id', 'left');
          $query = $this->db->get('wallet_funds_transfer');
          $result = $query->result_array();
          return $result ? $result : false;
     }


     function get_withdraw_request_by_user($id, $wallet_type)
     {
          return $this->db->get_where('withdraw_request', array('user_id' => $id, 'status' => 0, 'wallet_type' => $wallet_type))->row_array();
     }

     function getChildren($parentId)
     {
          $sql = "SELECT * FROM user_logs WHERE referral_id = {$parentId} UNION SELECT * FROM user_logs WHERE referral_id IN (SELECT ID FROM user_logs WHERE referral_id = {$parentId})";
          $result = $this->commonRawQuery($sql);
          return $result;
     }

     function saveRank($data)
     {
          $response = $this->db->insert('ranks', $data);
          return $response ? $response : false;
     }

     function insertPayment($data)
     {
          $response = $this->db->insert('stripe_payments', $data);
          return $response ? $response : false;
     }

     function add_to_business($userId, $data)
     {
          $user = $this->get_user_business($userId);
          if ($user) {
               $response = $this->db->query("UPDATE all_business SET amount = amount + {$data["amount"]} WHERE id = {$user['id']}");
               //$response = $query->result_array();
          } else {
               $response = $this->db->insert('all_business', $data);
          }
          return $response;
     }

     function get_user_business($id)
     {
          $data = $this->db->get_where('all_business', array('user_id' => $id))->row_array();
          return $data ? $data : false;
     }

     function current_month_commissions($id)
     {
          $this->db->where('user_id', $id);
          $this->db->where('MONTH(created_at)', date('m'));
          $this->db->where('YEAR(created_at)', date('Y'));
          $this->db->join('users', 'users.id = commission.from_id', 'left');
          $query = $this->db->get("commission");
          return $query->result_array();
     }

     function get_recent_team_members($id, $limit)
     {
          $data = array();
          $this->db->order_by("user_logs.id", "desc");
          $this->db->where("user_logs.referral_id", $id);
          $this->db->join('users', 'users.id=user_logs.user_id', 'left');
          $data = $this->db->get("user_logs", $limit, 0)->result_array();
          return $data ? $data : false;
     }
     public function getprice()
     {
          return      $query = $this->db->get('products')->result_array();
     }
     function add_wallet_amount($userId, $data)
     {
          $user = $this->get_user_wallet($userId);
          if ($user) {
               $response = $this->db->query("UPDATE topupwallet SET wallet_amount = wallet_amount + {$data["wallet_amount"]} WHERE id = {$user['id']}");
          } else {
               $response = $this->db->insert('topupwallet', $data);
          }
          return $response;
     }
     function get_user_daily_earnings($id)
     {
          $today = date('Y-m-d'); // Capital Y for 4-digit year
          return $this->db
               ->get_where('daily_growth', array(
                    'user_id' => $id,
                    'DATE(created_at)' => $today
               ))
               ->row_array();
     }
     function get_user_total_earning($id)
     {
        
         $data = $this->db
               ->get_where('daily_growth', array(
                    'user_id' => $id,
               ))
               ->result_array();

               return $data ? array_sum(array_column($data,'amount')) : 0;
     }
     function get_user_wallet($id)
     {
          return $this->db->get_where('topupwallet', array('user_id' => $id))->row_array();
     }
     function substract_wallet_amount($userId, $amount)
     {
          $user = $this->get_user_wallet($userId);
          $response = false;

          if ($user) {
               $response = $this->db->query("UPDATE topupwallet SET wallet_amount = wallet_amount - {$amount} WHERE user_id = {$userId}");
          }
          return $response;
     }

     function timetable_requests($data)
     {

          if ($this->db->insert('timetable_requests', $data)) {
               $id = $this->db->insert_id();
               $user = $this->db->get_where('timetable_requests', array('id' => $id))->row_array();
               return $user;
          }
          return false;
     }

     public function get_deposit_request_all()
     {
          $this->db->order_by("id", "desc");
          $data = $this->db->get("topup_requests")->result_array();
          return $data;
     }
     public function get_deposit_request_by_userid($user_id)
     {
          $this->db->order_by("id", "desc");
          $this->db->where("user_id", $user_id);
          $data = $this->db->get("topup_requests")->result_array();
          return $data;
     }
     function get_book_timing_requests($userid)
     {
          return $this->db->get_where('timetable_requests', array('user_id' => $userid))->result_array();
     }

     function check_status($user_id, $package_id)
     {
          $this->db->where('user_id', $user_id);
          $this->db->where('package_id', $package_id);
          $this->db->where('status', 1);
          $query =  $this->db->get('timetable_requests')->row_array();
          return $query;
     }

     function gettotalusers()
     {
          $this->db->where("id !=", 1);
          $data = $this->db->get("users")->result_array();
          return $data ? count($data) : 0;
     }
     function gettotalpaidusers()
     {
          $this->db->distinct();
          $this->db->select('user_id');
          $this->db->where("user_id !=", 1);
          $data = $this->db->get("memberships")->result_array();
          return $data ? count($data) : 0;
     }
     function gettotalpackagesold()
     {
          $data = $this->db->get("memberships")->result_array();
          return $data ? count($data) : 0;
     }
     function gettotalamountearned()
     {
          $this->db->select_sum('package_amount');
          $data = $this->db->get("memberships")->row_array();
          return $data ? $data["package_amount"] : 0;
     }
     function getreferrals($id)
     {
          $this->db->where("referral_id", $id);
          $result = $this->db->get("user_logs")->num_rows();
          return $result;
     }

     function getUserreferrals($id)
     {
          $this->db->where("referral_id", $id);
          $result = $this->db->get("user_logs")->result_array();
          return $result;
     }

     function get_all_commission($id)
     {
          $this->db->order_by("id", "desc");
          $this->db->where('to_id', $id);
          $query = $this->db->get('transaction');
          return $query->result_array();
     }
     function get_all_rows_wallet()
     {

          $this->db->where('wallet_amount >=', 1);
          $query = $this->db->get('topupwallet');
          return $query->result_array();
     }

     function get_investment_history($id)
     {
          $this->db->order_by("id", "desc");
          $this->db->where("user_id", $id);
          $result = $this->db->get("investment_history")->result_array();
          return $result;
     }

     function add_investment_amount($userId, $data)
     {
          $user = $this->get_investment($userId);
          if ($user) {
               $response = $this->db->query("UPDATE investment SET amount = amount + {$data["amount"]} WHERE id = {$user['id']}");
          } else {
               $response = $this->db->insert('investment', $data);
          }
          return $response;
     }
     function get_investment($id)
     {
          return $this->db->get_where('investment', array('user_id' => $id))->row_array();
     }

     function add_investment_history($data)
     {
          return $this->db->insert('investment_history', $data);
     }


     function get_deposit_request_accepted($id)
     {
          return $this->db->order_by("id", "desc")->get_where('topup_requests', array('user_id' => $id, 'status' => 1))->result_array();
     }
     function get_exchange_request_accepted($id)
     {
          return $this->db->order_by("id", "desc")->get_where('exchange_requests', array('user_id' => $id, 'status' => 1))->result_array();
     }

     function get_withdraw_by_userId($userId)
     {
          return $this->db->order_by("id", "desc")->get_where('withdrawal_request', array('user_id' => $userId))->row_array();
     }

     function saveCoinPayment($data)
     {

          $response = $this->db->insert('coinpayments', $data);

          return $response;
     }

     function saveCoinPaymentIPN($data)
     {

          $response = $this->db->insert('coinpayments_ipn', $data);

          return $response;
     }

     function get_accept_deposit($userId)
     {
          return $this->db->order_by("id", "desc")->get_where('coinpayments', array('user_id' => $userId, 'status' => 'success'))->row_array();
     }



     function getCoinPaymentByTxn($txn_id)
     {

          $data = $this->db->get_where('coinpayments', array('txn_id' => $txn_id))->row_array();

          return $data;
     }



     function updateCoinPayment($id, $data)
     {

          $this->db->where('id', $id);

          $this->db->update('coinpayments', $data);

          if ($this->db->affected_rows()) {

               return true;
          } else {

               return false;
          }
     }
     function get_banner()

     {

          $this->db->where("id", 1);

          $query = $this->db->get("banner")->row_array();

          return $query;
     }

     public function get_last_support_req($uid)
     {
          $this->db->order_by('id', 'desc');
          $this->db->where('user_id', $uid);
          $this->db->where('to_id', 1);
          $query = $this->db->get("support")->row_array();
          return $query;
     }

     function update_support_by_ticket($id, $data)
     {

          $this->db->where('ticket_no', $id);
          $this->db->update('support', $data);
          if ($this->db->affected_rows()) {
               return true;
          } else {
               return false;
          }
     }

     public function get_first_deposit_date($userId)
     {
          $this->db->select('date');
          $this->db->from('topup_requests');
          $this->db->where('user_id', $userId);
          $this->db->order_by('date', 'ASC'); // Order by date ascending to get the first deposit date
          $this->db->limit(1);
          $query = $this->db->get();

          if ($query->num_rows() > 0) {
               return $query->row_array();
          } else {
               return null;
          }
     }
}
