<?php

namespace App\Controllers;
use CodeIgniter\Session\Session;
use Config\Database;

class Home extends BaseController
{
    public function index()
    {  $this->db = Database::connect();


         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

         $number_of_users = "SELECT COUNT(*) as total FROM `users`  ";
        $data['number_of_new_offers'] = $this->db->query($number_of_users)->getRow();
         $number_of_market = "SELECT COUNT(*) as total FROM `loanrequest` ";
        $data['number_of_new_market'] = $this->db->query($number_of_market)->getRow();
        $number_of_payments = "SELECT COUNT(*) as total FROM `mpesatransaction`  ";
        $data['number_of_new_payments'] = $this->db->query($number_of_payments)->getRow();
           $quey = $this->db->query("SELECT * FROM `users`   ORDER BY name ASC LIMIT 5");
        $data['merch'] = $quey->getResultArray();
                    echo view('nav');
        return view('index',$data);}
         else {
            return redirect()->to("login");
        }
      
    }
    public function members()
    {  $this->db = Database::connect();


         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        
           $quey = $this->db->query("SELECT * FROM `users` ORDER BY id DESC ");
        $data['merch'] = $quey->getResultArray();
                    echo view('nav');
        return view('members',$data);}
         else {
            return redirect()->to("login");
        }
      
    }
    public function marketers()
    {  $this->db = Database::connect();


         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        
           $quey = $this->db->query("SELECT * FROM `users` WHERE  linkid = 'CEO'  ");
        $data['merch'] = $quey->getResultArray();
                    echo view('nav');
        return view('marketers',$data);}
         else {
            return redirect()->to("login");
        }
      
    }
      public function payments()
    {  $this->db = Database::connect();


         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        
           $quey = $this->db->query("SELECT * FROM `payments`  ");
        $data['merch'] = $quey->getResultArray();
                    echo view('nav');
        return view('payments',$data);}
         else {
            return redirect()->to("login");
        }
      
    }
      public function packages()
    {  $this->db = Database::connect();

        $memberid = (int) $this->request->getGet('id');

         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        
           $quey = $this->db->query("SELECT * FROM `loanrequest` WHERE userid = '$memberid' ");
        $data['merch'] = $quey->getResultArray();
                    echo view('nav');
        return view('packages',$data);}
         else {
            return redirect()->to("login");
        }
      
    }
        public function transactions()
    {  $this->db = Database::connect();

        $memberid = (int) $this->request->getGet('id');

         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        
           $quey = $this->db->query("SELECT * FROM `transactions` WHERE memberid = '$memberid' ");
        $data['merch'] = $quey->getResultArray();
                    echo view('nav');
        return view('transactions',$data);}
         else {
            return redirect()->to("login");
        }}
      public function earnings()
    {  $this->db = Database::connect();

        $memberid = (int) $this->request->getGet('id');

         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

         $query = $this->db->query("SELECT payments.id,payments.memberid,payments.agentid,payments.agentamount,payments.adminamount,payments.paymentstatus,payments.packagebought,payments.packageamount,payments.datecreated,payments.updateday,users.name
FROM payments
INNER JOIN users
ON users.id = payments.memberid WHERE payments.agentid= '$memberid'");
        $data['merch'] = $query->getResultArray();
           
                    echo view('nav');
        return view('earnings',$data);}
         else {
            return redirect()->to("login");
        }
    }
     public function withdraw()
    {  $this->db = Database::connect();

        $memberid = (int) $this->request->getGet('id');

         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];
 $number_of_payments = "SELECT SUM(amount) as total FROM `withdrawn` WHERE status='PAID'  AND memberid = '$memberid' ";
        $data['number_of_new_payments'] = $this->db->query($number_of_payments)->getRow();
         $number_of_payment = "SELECT SUM(amount) as total FROM `withdrawn` WHERE status='UNPAID'  AND memberid = '$memberid' ";
        $data['number_of_new_payment'] = $this->db->query($number_of_payment)->getRow();
         $query = $this->db->query("SELECT withdrawn.id,withdrawn.memberid,withdrawn.phonenumber,withdrawn.amount,withdrawn.status,withdrawn.datecreated,users.name
FROM withdrawn
INNER JOIN users
ON users.id = withdrawn.memberid WHERE withdrawn.memberid= '$memberid'");
        $data['merch'] = $query->getResultArray();
         $quey = $this->db->query("SELECT * FROM `balance` WHERE memberid = '$memberid' ");
        $data['merc'] = $quey->getResultArray();
           
                    echo view('nav');
        return view('withdraw',$data);}
         else {
            return redirect()->to("login");
        }
    }
         public function login()
    {

        echo view('login');
    }
      public function post_register()
    {
        $request = $this->request;
        $fullname = $request->getPost('fullname');
        $email = $request->getPost('email');
        $password = password_hash($request->getPost('password'), PASSWORD_DEFAULT);
        $adminModel = new \App\Models\UserModel();
        $admin = $adminModel
            ->where('email', $email)
            ->where('fullname', $fullname)
            ->first();
        if ($admin) {
            return redirect()->to(base_url() . '/register?message=' . base64_encode('User Already Registered'));
        } else {
            $data = [
                'fullname' => $fullname ,
                'email' => $email,
                'password' => $password,
            ];
            $session = Session();
            $admin_id = $adminModel->insert($data);
            if ($admin_id) {
                    $data['id'] = $admin_id;
                                        $data['fullname'] = $fullname;

                    $session->set('admin', $data);
                    return redirect()->to(base_url() . '/index');
               
            } else {
                return redirect()->to(base_url() . '/register?message=' . base64_encode('Unable to Save New admin'));
            }

        }

    }
      public function register()
    {
 $mRequest = $this->request;
        if ($mRequest->getGet('message') === null) {
            $message = "";
        } else {
            $message = base64_decode($mRequest->getGet('message'));
        }
        $data['message'] = $message;
        return view('register', $data);
    }
     public function updatepaymentstatus()
    {$this->db = Database::connect();
        $session = session();
        $request = $this->request;
        $id = $request->getPost('id');
       $linkid = $this->request->getGet('id');

  $q = "UPDATE payments SET paymentstatus = 'PAID'  WHERE id = '$id' AND agentid= '$linkid';";
     $std_ =   $this->db->query($q);
     if ($std_) {
         $session->setFlashdata('msg', 'UPDATED');
                return redirect()->to('/earnings?id='.$linkid.'');
     }
    }
      public function updatewithdrawstatus()
    {$this->db = Database::connect();
        $session = session();
        $request = $this->request;
        $id = $request->getPost('id');
       $linkid = $this->request->getGet('id');

  $q = "UPDATE withdraw SET status = 'PAID'  WHERE id = '$id' AND memberid= '$linkid';";
     $std_ =   $this->db->query($q);
     if ($std_) {
         $session->setFlashdata('msg', 'UPDATED');
                return redirect()->to('/withdraw?id='.$linkid.'');
     }
    }
     public function addjournalpost()
    {$this->db = Database::connect();
        $session = Session();
       $userid = 2;
               $request = $this->request;

         $caption = $request->getPost('caption');


            $img = $this->request->getFile('jornalfile');
            $img->move('../public/today/');
  $saoke= $img->getName();
          
        $q = "UPDATE todayproducts SET todayimage = '$saoke', caption = '$caption'  WHERE id = '$userid';";
     $std_ =   $this->db->query($q);

        if ($std_) {
            
 $session->setFlashdata('m', 'Video Uploaded ');
                            return redirect()->to("/addproducts");
         
        } else {
            return redirect()->to("/");
        }
    }
    public function addproducts()
    {  $this->db = Database::connect();


         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        
           
                    echo view('nav');
        return view('addproducts');}
         else {
            return redirect()->to("login");
        }
      
    }
      public function viewproducts()
    {  $this->db = Database::connect();

        $memberid = (int) $this->request->getGet('id');

         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        
           $quey = $this->db->query("SELECT * FROM `todayproducts`  ");
        $data['merch'] = $quey->getResultArray();
                    echo view('nav');
        return view('viewproducts',$data);}
         else {
            return redirect()->to("login");
        }
    }
     public function postdeposit()
    {
$this->db = Database::connect();
 $session = Session();
        $admin = $session->get('admin');
        $request = $this->request;
                    $adminid= $admin['id'];

        $userid = $request->getPost('userid');
                $amount = $request->getPost('amount');
                 $qeyy = $this->db->query("SELECT * FROM `users` WHERE id ='$userid'");
        $users = $qeyy->getResultArray();
        foreach ($users as $r){

            $mpesabalance =  $r['mpesabalance'];

$newbalance = $mpesabalance+ $amount;
$q = "UPDATE users SET mpesabalance = '$newbalance'  WHERE id = '$userid';";
     $std_ =   $this->db->query($q);

     if ( $std_) {
 $session->setFlashdata('m', 'Deposit Successful   ');
                            return redirect()->to("/marketers");     }

            }


        }
          public function addnotificationpost()
    {$this->db = Database::connect();
        $session = Session();

        $admin = $session->get('admin');
        $request = $this->request;
                    $id= 1;

        $notification = $request->getPost('notification');
       

          
  $q = "UPDATE notification SET message = '$notification'  WHERE id = '$id';";
     $std_ =   $this->db->query($q);  
        if ($std_) {
            
 $session->setFlashdata('m', 'Notification Uploaded ');
                            return redirect()->to("/addnotification");
         
        } else {
            return redirect()->to("/");
        }
    }
      public function addnotification()
    {  $this->db = Database::connect();

        $memberid = (int) $this->request->getGet('id');

         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        
         
                    echo view('nav');
        return view('addnotification');}
         else {
            return redirect()->to("login");
        }}
          public function adddeposit()
    {  $this->db = Database::connect();

        $memberid = (int) $this->request->getGet('id');

         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        
         
                    echo view('nav');
        return view('adddeposit');}
         else {
            return redirect()->to("login");
        }
    }
            public function adddepositpost()
    {$this->db = Database::connect();
        $session = Session();

        $admin = $session->get('admin');
        $request = $this->request;
                           $memberid = (int) $this->request->getGet('id');


        $amount = $request->getPost('amount');
       
       $qeyy = $this->db->query("SELECT * FROM `users` WHERE id ='$memberid'");
        $users = $qeyy->getResultArray();
        foreach ($users as $r){

            $mpesabalance =  $r['mpesabalance'];

$newbalance = $mpesabalance+ $amount;
$q = "UPDATE users SET mpesabalance = '$newbalance'  WHERE id = '$memberid';";
     $std_ =   $this->db->query($q);
        if ($std_) {
            
 $session->setFlashdata('m', 'Deposit Added ');
                            return redirect()->to("/marketers");
         
        } else {
            return redirect()->to("/");
        }  }
    }
     public function editmember()
    {  $this->db = Database::connect();

        $memberid = (int) $this->request->getGet('id');

         $session = Session();
        $admin = $session->get('admin');
        if ($admin) {
                    $adminid= $admin['id'];

        $qeyy = $this->db->query("SELECT * FROM `users` WHERE id ='$memberid'");
        $data['users'] = $qeyy->getResultArray();
         $qey = $this->db->query("SELECT * FROM `loans` WHERE userid ='$memberid'");
        $data['uers'] = $qey->getResultArray();
        
         
                    echo view('nav');
        return view('editmember',$data);}
         else {
            return redirect()->to("login");
        }
    }
     public function editmemberpost()
    {$this->db = Database::connect();
        $session = Session();

        $admin = $session->get('admin');
        $request = $this->request;
                           $memberid = (int) $this->request->getGet('id');

 $name = $request->getPost('name');
  $username = $request->getPost('username');
   $emailaddress = $request->getPost('emailaddress');

        $phonenumber = $request->getPost('phonenumber');
       $mpesabalance = $request->getPost('mpesabalance');
    
       $whatsapp = $request->getPost('whatsapp');


$ql = "UPDATE whatsapp SET total = '$whatsapp'WHERE memberid = '$memberid';";
     $std =   $this->db->query($ql);
     $q = "UPDATE users SET mpesabalance = '$mpesabalance',phonenumber = '$phonenumber',emailaddress = '$emailaddress',username = '$username',name = '$name'  WHERE id = '$memberid';";
     $std_ =   $this->db->query($q);
        if ($std_) {
            
 $session->setFlashdata('m', 'Changes Uploaded Successfully ');
return redirect()->to('/editmember?id='.$memberid.'');         
        } else {
            return redirect()->to("/");
        }  
    }

     public function withdrawpost()
{

$this->db = Database::connect();
 $session = Session();
        $request = $this->request;


  $id = $request->getPost('id');
       $linkid = $this->request->getGet('id');

 

        $amount = $request->getPost('amount');
         $mobilephone = $request->getPost('phonenumber');

        $initiatorPassword = "Benja(munyao254"; // From M-Pesa portal
$publicKey = file_get_contents("ProductionCertificate.cer"); // Path to Safaricom's .cer file

openssl_public_encrypt($initiatorPassword, $encrypted, $publicKey, OPENSSL_PKCS1_PADDING);

$securityCredential = base64_encode($encrypted);

  
        $adminid = 1;
         $qey = $this->db->query("SELECT * FROM `admin` WHERE id ='$adminid'");
        $usrs = $qey->getResultArray();
          foreach ($usrs as $rr){
            $adminbalance = $rr['balance'];
        }

     
  $mobilephone = (substr($mobilephone, 0, 1) == "+") ? str_replace("+", "", $mobilephone) : $mobilephone;
    $mobilephone = (substr($mobilephone, 0, 1) == "0") ? preg_replace("/^0/", "254", $mobilephone) : $mobilephone;
    $mobilephone = (substr($mobilephone, 0, 1) == "7") ? "254{$mobilephone}" : $mobilephone;
//YOU MPESA API KEYS
$consumerKey = "p8AKKyWGm33GyScECPAwVEumLVxccAr1huWjFALgC6B1oEap";
$consumerSecret = "0eugzQ4pwAgDnuVU0is3vPTMboJN5Vq3ShpXqsLmldfPz0E6G1c7LH7XEnKG1yAY";
//ACCESS TOKEN URL
$access_token_url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
$headers = ['Content-Type:application/json; charset=utf8'];
$curl = curl_init($access_token_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_USERPWD, $consumerKey . ':' . $consumerSecret);
$result = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

$result = json_decode($result);
$access_token = $result->access_token;
$processrequestUrl = 'https://api.safaricom.co.ke/mpesa/b2c/v1/paymentrequest';
$callbackurl = 'https://mpesa.brewburgadverts.com/callback.php';
$passkey = "a4551c6d0d5256eb3feab24eead3eb10043e0f7882f881bd3d2682f29968b136";
$BusinessShortCode = '4182097';
$Timestamp = date('YmdHis');
// ENCRIPT  DATA TO GET PASSWORD
$Password = base64_encode($BusinessShortCode.$passkey.$Timestamp);
$mobilphone= $mobilephone;

$PartyA = $mobilphone;
 $rand=rand(1111,999);
 $AccountReference = "WITHDRAWAL";
$TransactionDesc = 'GEMINI BYTES';
$Amount = $amount;
$stkpushheader = ['Content-Type:application/json', 'Authorization:Bearer ' . $access_token];

//INITIATE CURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $processrequestUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, $stkpushheader); //setting custom header
$curl_post_data = array(
  //Fill in the request parameters with valid values

  "InitiatorName" => "BENJAMINFESTU",
    "SecurityCredential" => $securityCredential,
    "CommandID" => "SalaryPayment",
    "Amount" => $amount,
    "PartyA" => $BusinessShortCode,
    "PartyB" => $mobilephone,
    "Remarks" => "Payment from Company",
    "QueueTimeOutURL" => "https://mpesa.brewburgadverts.com/b2c-result/",
    "ResultURL" => "https://mpesa.brewburgadverts.com/b2c-result/callback.php",
    "Occasion" => "Salary",

);


$data_string = json_encode($curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
$curl_response = curl_exec($curl);

$data_to = json_decode($curl_response);
if (isset($data_to->OriginatorConversationID)) {
    $originatorConversationId = $data_to->OriginatorConversationID;
    // Save it in your DB for later use
    file_put_contents("originator_id.txt", $originatorConversationId);
}

if (isset($data_to->ResponseCode)) {
  $ResultCode = $data_to->ResponseCode;


  


     
     $q = "UPDATE withdrawn SET status = 'PAID'  WHERE id = '$id' AND memberid= '$linkid';";
     $std_ =   $this->db->query($q);
     if ($std_) {
         $session->setFlashdata('msg', 'MPESA PAID');
                return redirect()->to('/withdraw?id='.$linkid.'');
     }

 
        

     }



}}

    

