<?php

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\SMTP;

use PHPMailer\PHPMailer\Exception;

include 'vendor/autoload.php';

   class User{

      private $con;

      public $email;

      public $password;

      public $name;

      public $first_name;

      public $sex;



      public $image;

      public $country;

      public $phone;

      public $address;



    public function __construct($db){

        $this->con = $db;

    }



    public function CreateAccount(){

        $user_id = random_int(000000,999999);

        $status = 'inactive';


        $acc =  random_int(1111111111,9999999999);

        $code =  random_int(11111,99999);
        $c =1;

        try{

            $stmt = $this->con->prepare('insert into users(user_id,email,account_no,sort_code,password,first_name,sex,image,country,phone,address,status,transfer,otp)values(:user_id,:email,:account_no,:sort_code,:password,:first_name,:sex,:image,:country,:phone,:address,:status,:transfer,:otp)');

            $stmt->bindParam(':user_id',$user_id);

            $stmt->bindParam('email',$this->email);

            $stmt->bindParam(':account_no',$acc);

            $stmt->bindParam(':sort_code',$code);

            $stmt->bindParam(':password',$this->password);

            $stmt->bindParam(':first_name',$this->first_name);

            $stmt->bindParam(':sex',$this->sex);

            $stmt->bindParam(':image',$this->image);

            $stmt->bindParam(':country',$this->country);

            $stmt->bindParam(':phone',$this->phone);



            $stmt->bindParam(':address',$this->address);



            $stmt->bindParam(':status',$status);


            $stmt->bindParam(':transfer',$c);


            $stmt->bindParam(':otp',$c);

            $stmt->execute();


            $id = $this->con->lastinsertId();

            $_SESSION['id']        = $id;


            $this->balance('loan_balance',$id);

            $this->balance('balance',$id);

            $this->mailConnect($this->email,$this->name,$this->password,$id);

            // $this->mailConnect2($this->email,$this->name,$this->password,$id);

            return true;

        }catch(PDOException $e){

            echo "error1 ". $e->getMessage();

        }

    }

    public function hasPendingTransaction() {

        $user_id = $_SESSION['id'];

        try {
            $stmt = $this->con->prepare("SELECT *  FROM transaction WHERE user_id = :user_id AND status = 'pending'");
            $stmt->bindParam(':user_id', $user_id);
            $stmt->execute();
            $row = $stmt->fetchAll(PDO::FETCH_OBJ);
            return $row ; // Return true if there are pending transactions, false otherwise
        } catch (PDOException $e) {
            echo "error checking pending transaction: " . $e->getMessage();
            return false;
        }
    }

    public function singleTransaction($id) {

        try {
            $stmt = $this->con->prepare("SELECT *  FROM transaction WHERE id = :id");
            $stmt->bindParam(':id', $id);
            $stmt->execute();
            $row = $stmt->fetch(PDO::FETCH_OBJ);
            return $row ; // Return true if there are pending transactions, false otherwise
        } catch (PDOException $e) {
            echo "error checking pending transaction: " . $e->getMessage();
            return false;
        }
    }
    public function Complete($id) {
       try {
          $stmt = $this->con->prepare("UPDATE transaction SET status ='complete' WHERE id = :id ");
          $stmt->bindParam(':id', $id);
          $stmt->execute();
          return true;
       } catch (PDOException $e) {
          echo "error updating transaction status: " . $e->getMessage();
          return false;
       }
    }

    public function updateBalance($amount, $user_id, $type) {
        try {
            if ($type == 'debit') {
            } else if ($type == 'credit') {
                $stmt = $this->con->prepare('update balance set balance = balance + :amount where user_id = :user_id'); 
            } else {
                throw new Exception('Invalid transaction type');
            }
            
            $stmt->bindParam(':user_id', $user_id);
            $stmt->bindParam(':amount', $amount);
            $stmt->execute();
            return true;
        } catch(PDOException $e) {
            echo "Error updating balance: " . $e->getMessage();
            return false;
        } catch(Exception $e) {
            echo $e->getMessage();
            return false;
        }
    }
     


    public function mailConnect($email,$name,$password,$id){

        $phpmailer = new PHPMailer();

        $phpmailer->isSMTP();

        $phpmailer->Host = 'mail.capitalfinbnk.com';

        $phpmailer->SMTPAuth = true;

        $phpmailer->Port = 465;

        $phpmailer->Username = 'support@capitalfinbnk.com';

        $phpmailer->Password = 'Coming12341@';
          // IMPORTANT: For port 465 you MUST use SSL
        $phpmailer->SMTPSecure = 'ssl';


        // Set the recipient's email address
        $phpmailer->addAddress($email,$name);

        $phpmailer->setFrom('support@capitalfinbnk.com','Capital Finance Bank.');


        // Set the email subject
        $phpmailer->Subject = 'Registration Successful';

        $phpmailer->isHTML(true);

        $phpmailer->Body = "

        <html> 

            <head> 

                <title>Quick link</title> 

            </head> 

            <body>

             <p> Welcome to en.capitalfinbnk.com Online Banking Services.</p>


                <p>Our online banking service allows you to access your account history and transactions from anywhere. This is the quickest way to see whether a transaction has cleared your account. It also enables you to find out about any unauthorized transactions more quickly, so you can dispute them right away.</p>



                <p>You can quickly transfer money between accounts when you do it online. It's more convenient than going to a bank in person or using an automated phone service, which requires you to provide information when prompted. </p>



                <p>Our services are highly secured, we use encryption devices to ensure that all client information is protected and there is no security breach. This ultimately provides you security from online frauds and account hacking.</p>



                <h3> Below are your login credentials</h3>

                
				<p>Acount Number: ".$this->getUseId($id)->account_no." <br>Login Password:$password </p>


                <p>Transaction PIN: ".$this->getUseId($id)->user_id. "  </p>
				
				<p>To access your new account please use the following link and click on internet banking:https://en.capitalfinbnk.com/</p>
				
				<p>Having trouble accessing your new account? <br>Or visit our website: https://en.capitalfinbnk.com/ <br><b>Thanks for applying for Capital Finance Bank.  Online Banking Services!</p>



            </body> 

        </html>";



        if (!$phpmailer->send()) {

            echo 'Error: ' . $phpmailer->ErrorInfo;

         } else {

            echo 'Email sent successfully';

         }



    }

     public function transferReceipt($email, $country, $name, $bank, $account, $amount)
    {

        // Replace with your own email address and name
        $phpmailer = new PHPMailer();

        $phpmailer->isSMTP();

        $phpmailer->Host = 'mail.capitalfinbnk.com';

        $phpmailer->SMTPAuth = true;

        $phpmailer->Port = 465;

        $phpmailer->Username = 'support@capitalfinbnk.com';

        $phpmailer->Password = 'Coming12341@';
          // IMPORTANT: For port 465 you MUST use SSL
        $phpmailer->SMTPSecure = 'ssl';

        // Set the recipient's email address

        $phpmailer->addAddress($email, $name);


        $phpmailer->setFrom('support@capitalfinbnk.com', 'Capital Finance Bank. ');


        // Set the email subject

        $phpmailer->Subject = 'Clients Transfer Information';

        $phpmailer->isHTML(true);


        $phpmailer->Body = "
        <html> 
            <head> 
                <title>Quick link</title> 
            </head> 
            <body>
                <h3> Below are Client Transfer Information</h3>
                <p>Recipient Name: " . $name . " </p>
                <p>Country: " . $country . " </p>
                <p>Account Number: " . $account . "</p>
                <p>Bank: " . $bank . "</p>
                <p>Amount: $" . number_format($amount) . "</p>

            </body> 

        </html>";

        if (!$phpmailer->send()) {

            echo 'Error: ' . $phpmailer->ErrorInfo;
        } else {

            echo 'Email sent successfully';
        }

    }


    public function mailConnect2($email,$password,$id,$name = null){

        // Replace with your own email address and name

        $from = "support@capitalfinbnk.com";

        $fromName = "Capital Finance Bank.";



        // Replace with a subject for the email

        $subject = "Registration successful";



        $Body = "

        <html> 

            <head> 

                <title>Quick link</title> 

            </head> 

            <body>

             <p> Welcome $name </p>



                <p>Our online banking service allows you to access your account history and transactions from anywhere. This is the quickest way to see whether a transaction has cleared your account. It also enables you to find out about any unauthorized transactions more quickly, so you can dispute them right away.</p>



                <p>You can quickly transfer money between accounts when you do it online. It's more convenient than going to a bank in person or using an automated phone service, which requires you to provide information when prompted. </p>



                <p>Our services are highly secured, we use encryption devices to ensure that all client information is protected and there is no security breach. This ultimately provides you security from online frauds and account hacking.</p>



                <h3> Below are your login credentials</h3>

                <p>User Acount Number: ".$this->getUseId($id)->account_no."</p>



                <p>Login Password:$password  </p>



                <p>Transaction PIN: ".$this->getUseId($id)->user_id. "  </p>



            </body> 

        </html>";



        $headers = "MIME-Version: 1.0" . "\r\n";

        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

        $headers .= "From: $fromName <$from>" . "\r\n";



        mail($email, $subject, $Body, $headers);


    }

    // check whether email exist

    public function emailExist($email){

        try{

        $stmt = $this->con->prepare("select email from users where email =:email");

        $stmt->bindParam(":email",$email);

        $stmt->execute();

            if($stmt->rowCount() > 0){

                return true;

            }else{

                return false;

            }

        }catch(PDOException $e){

            echo 'error has occured '. $e->getMessage();

        }

    }


    public function getUseId($id){ // get userid from db

        try{

        $stmt = $this->con->prepare("select * from users where id =:id");

        $stmt->bindParam(":id",$id);

        $stmt->execute();



        $result = $stmt->fetch(PDO::FETCH_OBJ);



        return $result;

        

        }catch(PDOException $e){

            echo 'error '. $e->getMessage();

        }

    }


    public function getByEmail($email){

        try{

          $stmt = $this->con->prepare("select * from users where email = '$email'");

          $stmt->execute();

          if($stmt->rowCount() > 0){

               $r  = $stmt->fetch(PDO::FETCH_OBJ);

               return $r;

          }

        }catch(PDOException $e){

             echo 'error '. $e->getMessage();

        }

    }


    public function getByAccountNo($no){

        try{

          $stmt = $this->con->prepare("select * from users where account_no = '$no'");

          $stmt->execute();

          if($stmt->rowCount() > 0){

               $r  = $stmt->fetch(PDO::FETCH_OBJ);

               return $r->id;

          }else{

            return 'not';

          }

        }catch(PDOException $e){

             echo 'error '. $e->getMessage();

        }

    }

    // public function sendRegForgot($email,$name = null){

    //     $phpmailer = new PHPMailer();

    //     $phpmailer->isSMTP();

    //     $phpmailer->Host = 'mail.capitalfinbnk.com';

    //     $phpmailer->SMTPAuth = true;

    //     $phpmailer->Port = 465;

    //     $phpmailer->Username = 'support@capitalfinbnk.com';

    //     $phpmailer->Password = 'Coming12341@';
        
    //     $phpmailer->SMTPSecure = 'ssl';

    //     // Set the recipient's email address

    //     $phpmailer->addAddress($email,$name);

    //     $phpmailer->setFrom('support@capitalfinbnk.com','Capital Finance Bank. ');

    //     // Set the email subject

    //     $phpmailer->Subject = 'Forgot Password/Login ID';

    //     $phpmailer->isHTML(true);



    //     $phpmailer->Body  = "

    //         <html> 

    //             <head> 

    //                 <title>Quick link</title> 

    //             </head> 

    //             <body> 

    //                 <p>You can quickly transfer money between accounts when you do it online. It's more convenient than going to a bank in person or using an automated phone service, which requires you to provide information when prompted. </p>



    //                 <p>Our services are highly secured, we use encryption devices to ensure that all client information is protected and there is no security breach. This ultimately provides you security from online frauds and account hacking.</p>



    //                 <p> Below are your login credentials .</p>



    //                 <p><strong>Your User ID is </strong>" .$this->getByEmail($email)->account_no."<br>

    //                 <strong>Your Login Password is </strong> " .$this->getByEmail($email)->password.  "  

    //                 </p>  

    //                 <p>Happy Banking</p>

    //                 <p>Capital Finance Bank.</p>

    //             </body> 

    //         </html>

    //      ";



    //     if (!$phpmailer->send()) {

    //     echo 'Error: ' . $phpmailer->ErrorInfo;

    //     } else {

    //     echo 'Email sent successfully';

    //      }

    // }
    
    public function sendRegForgot($email, $name = null){

    $phpmailer = new PHPMailer(true);

    // Turn on debug (0 = off, 2 = show errors)
    $phpmailer->SMTPDebug = 2;
    
    $phpmailer->isSMTP();
    $phpmailer->Host = 'mail.capitalfinbnk.com';
    $phpmailer->SMTPAuth = true;
    $phpmailer->Username = 'support@capitalfinbnk.com';
    $phpmailer->Password = 'Coming12341@';

    // Correct encryption for port 465
    $phpmailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $phpmailer->Port = 465;

    $phpmailer->setFrom('support@capitalfinbnk.com', 'Capital Finance Bank');
    $phpmailer->addAddress($email, $name);
    $phpmailer->isHTML(true);
    $phpmailer->Subject = 'Forgot Password/Login ID';

    $user = $this->getByEmail($email);

    $phpmailer->Body = "
        <html>
            <body>
                <p>You can quickly transfer money between accounts when you do it online...</p>

                <p><strong>Your User ID is:</strong> {$user->account_no}<br>
                <strong>Your Login Password is:</strong> {$user->password}</p>

                <p>Happy Banking<br>Capital Finance Bank</p>
            </body>
        </html>
    ";

    try {
        $phpmailer->send();
        echo 'Email sent successfully';
    } catch (Exception $e) {
        echo "Mailer Error: {$phpmailer->ErrorInfo}";
    }
}





    public function sendOtherRegForgot($email,$name = null){

        

        // Replace with your own email address and name

        $from = "support@capitalfinbnk.com";

        $fromName = "Capital Finance Bank.";





        // Replace with a subject for the email

        $subject = "Forgot Password ";

        $Body  = "

            <html> 

                <head> 

                    <title>Quick link</title> 

                </head> 

                <body> 



                    <p>Our services are highly secured, we use encryption devices to ensure that all client information is protected and there is no security breach. This ultimately provides you security from online frauds and account hacking.</p>



                    <p> Below are your login credentials .</p>



                    <p><strong>Your User ID is </strong>" .$this->getByEmail($email)->account_no."<br>

                    <strong>Your Login Password is </strong> " .$this->getByEmail($email)->password.  "  

                    </p>  

                    <p>Happy Banking</p>

                    <p>Capital Finance Bank.</p>

                </body> 

            </html>

         ";



        $headers = "MIME-Version: 1.0" . "\r\n";

        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

        $headers .= "From: $fromName <$from>" . "\r\n";



        mail($email, $subject, $Body, $headers);





    }



    public function sendOtherOTP($email,$name=null){ // send otp

        $phpmailer = new PHPMailer();

        $phpmailer->isSMTP();


        $phpmailer->Host = 'mail.capitalfinbnk.com';

        $phpmailer->SMTPAuth = true;

        $phpmailer->Port = 465;

        $phpmailer->Username = 'support@capitalfinbnk.com';

        $phpmailer->Password = 'Coming12341@';
          // IMPORTANT: For port 465 you MUST use SSL
        $phpmailer->SMTPSecure = 'ssl';


        // Set the recipient's email address

        $phpmailer->addAddress($email,$name);



        $phpmailer->setFrom('support@capitalfinbnk.com','Capital Finance Bank. ');



        // Set the email subject

        $phpmailer->Subject = 'Swift MT103 Code Required';



        $phpmailer->isHTML(true);



        $phpmailer->Body  = "

        <html> 

            <head> 

                <title>Quick link</title> 

            </head> 

            <body> 

                <p>Enter the Swift MT103 Code to authorize your transfer.</p>

                <p>".$this->mtOtp($email)."</p>

                <p>Happy Banking</p>

                <p>Capital Finance Bank. </p>

            </body> 

        </html>";

        

        if (!$phpmailer->send()) {

           echo 'Error: ' . $phpmailer->ErrorInfo;

        } else {

           echo 'Email sent successfully';

        }

    }



    public function sendOTP($email){ // send otp

        $from = "support@capitalfinbnk.com";

        $fromName = "Capital Finance Bank.";

        $subject = "Swift MT103 Code Required";

        $Body = "

        <html> 

            <head> 

                <title>Quick link</title> 

            </head> 

            <body> 

                <p>Enter the Swift MT103 Code to authorize your transfer.</p>

                <p>".$this->mtOtp($email)."</p>

                <p>Happy Banking</p>

                <p>Capital Finance Bank.</p>

            </body> 

        </html>";

        

        $headers = 'MIME-Version: 1.0' . "\r\n";

        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";



        //Additional headers

        $headers = "MIME-Version: 1.0" . "\r\n";

        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

        $headers .= "From: $fromName <$from>" . "\r\n";



        mail($email, $subject, $Body, $headers);

    }

    // login script

     public function login($account){

        try{

            $stmt = $this->con->prepare("select * from users where account_no=:account_no");

            $stmt->bindParam(":account_no",$account);

            $stmt->execute();



            if($stmt->rowCount() < 1){ 

                return "not";

            }else{

                $row = $stmt->fetch(PDO::FETCH_OBJ);

                if($this->password == $row->password){ 



                    if($row->isadmin == '1' ||  $row->isadmin == '2'){



                        $_SESSION['first_name']  = $row->first_name;



                        $_SESSION['user_id']     = $row->user_id;

                        $_SESSION['id']          = $row->id;



                        $_SESSION['email']       = $row->email;

                        $_SESSION['country']     = $row->country;

                        $_SESSION['phone']       = $row->phone;

                        $_SESSION['image']       = $row->image;

                        $_SESSION['account']     = $row->account_no;

                        $_SESSION['sort']        = $row->sort_code;

                        $_SESSION['admin']       =  $row->isadmin;

                        $_SESSION['address']     = $row->address;

                        $_SESSION['password']    = $row->password;



                        $_SESSION['date']       =  $row->login_time ?? '';



                        return 'admin';

                    }else{

                        $s = $this->con->prepare("select * from loan_balance where user_id='$row->id'");

                        $s->execute();

                        $rows = $s->fetch(PDO::FETCH_OBJ);



                        $_SESSION['loan']        = $rows->balance;



                        $_SESSION['first_name']  = $row->first_name;



                        $_SESSION['user_id']    = $row->user_id;

                        $_SESSION['id']         = $row->id;



                        $_SESSION['email']      = $row->email;

                        $_SESSION['country']    = $row->country;

                        $_SESSION['phone']      = $row->phone;

                        $_SESSION['image']        = $row->image;

                        $_SESSION['account']    = $row->account_no;

                        $_SESSION['sort']       = $row->sort_code;

                        $_SESSION['address']    = $row->address;

                        $_SESSION['password']   = $row->password;

                        $_SESSION['status']     = $row->status;





                        $_SESSION['date']       =  $row->login_time ?? '';



                        return 'user';

                    }

                }else{

                    return false;

                }

            }

        }catch(PDOException $e){

            echo 'login error '. $e->getMessage();

        }

    }



    public function balance($table,$id){// create balance

        $balance = 0;

        try{

            $stmt = $this->con->prepare("insert into $table(user_id,balance)values(:user_id,:balance)");

            $stmt->bindParam(':user_id',$id);

            $stmt->bindParam(':balance',$balance);

            $stmt->execute();



        }catch(PDOException $e){

            echo "error1 ". $e->getMessage();

        }

    }



    public function getBalance($table,$id){ // get account balance

         try{

            $stmt = $this->con->prepare("select balance from $table where user_id =$id");

            $stmt->execute();

            $data  = $stmt->fetch(PDO::FETCH_OBJ);



            return $data->balance;



        }catch(PDOException $e){

            echo "error balance ". $e->getMessage();

        }

    }



    public function fundTransfer($amount){ // transfer balance

        $id = $_SESSION['id'];

         try{

            $stmt = $this->con->prepare("update balance set balance = (balance - $amount) where user_id =:user_id");

            $stmt->bindParam(':user_id',$id);

            $stmt->execute();



            return true;



        }catch(PDOException $e){

            echo "error balance ". $e->getMessage();

        }

    }



    public function mtOtp(){ // set otp

        $otp = random_int(00000,99999);



        $_SESSION['otp'] = $otp;



        return $otp;

    }



    // public function InterTransfer($name,$sort,$account,$amount,$bank,$country,$city,$ref){ // create transfer recodes

    //     $id = $_SESSION['id'];

    //     $email = $_SESSION['email'];

    //     $reference = uniqid();

    //     $date = new DateTime();

    //     $c = $date->format('d M y, h:i a'); // 21 Dec 22, 08:39 pm

    //     $status = 'complete';

    //     try{

    //         $stmt = $this->con->prepare('insert into transfer_request(user_id,name,email,sort_code,account_no,amount,bank_name,country,city,ref)values(:user_id,:name,:email,:sort_code,:account_no,:amount,:bank_name,:country,:city,:ref)');

    //         $stmt->bindParam(':user_id',$id);

    //         $stmt->bindParam(':name',$name);

    //         $stmt->bindParam(':email',$email);



    //         $stmt->bindParam('sort_code',$sort);

    //         $stmt->bindParam(':account_no',$account);

    //         $stmt->bindParam(':amount',$amount);

    //         $stmt->bindParam(':bank_name',$bank);

    //         $stmt->bindParam(':country',$country);

    //         $stmt->bindParam(':city',$city);

    //         $stmt->bindParam(':ref',$ref);



    //         $stmt->execute();



    //         // $this->fundTransfer($amount);



    //         // $this->createTransaction($amount,$id,$reference,$bank,$c,$status,'Debit');



    //         $this->activities('Your transaction has been successfully processed. Thank you for banking with us. Note, all transactions are subject to  confirmation and fraud proof verification.','Success',$id);



    //         // $this->noti($email,$name=null);

    //          $this->sendNoti($email);



    //         return true;



    //         // $id = $this->con->lastinsertId();



    //         return true;

    //     }catch(PDOException $e){

    //         echo "error1 ". $e->getMessage();

    //     }

    // }
    
      public function InterTransfer($trans_id,$name,$sort,$account,$amount,$bank,$country,$city,$ref){ // create transfer recodes

        $id = $_SESSION['id'];

        $email = $_SESSION['email'];

        $reference = uniqid();

        $date = new DateTime();

        $c = $date->format('d M y, h:i a'); // 21 Dec 22, 08:39 pm

        $status = 'complete';

        try{

            $stmt = $this->con->prepare('insert into transfer_request(user_id,trans_id,name,email,sort_code,account_no,amount,bank_name,country,city,ref)values(:user_id,:trans_id,:name,:email,:sort_code,:account_no,:amount,:bank_name,:country,:city,:ref)');

            $stmt->bindParam(':user_id',$id);
            $stmt->bindParam(':trans_id',$trans_id);


            $stmt->bindParam(':name',$name);

            $stmt->bindParam(':email',$email);

            $stmt->bindParam('sort_code',$sort);

            $stmt->bindParam(':account_no',$account);

            $stmt->bindParam(':amount',$amount);

            $stmt->bindParam(':bank_name',$bank);

            $stmt->bindParam(':country',$country);

            $stmt->bindParam(':city',$city);

            $stmt->bindParam(':ref',$ref);


            $stmt->execute();

           //.
          // $this->activities('Your transaction has been successfully processed. Thank you for banking with us. Note, all transactions are subject to  confirmation and fraud proof verification.','Success',$id);



           // $this->noti($email,$name=null);

            // $this->sendNoti($email);



            return true;



            // $id = $this->con->lastinsertId();



            return true;

        }catch(PDOException $e){

            echo "error1 ". $e->getMessage();

        }

    }



    public function delete_transfer_request($id){

        try{

             $stmt = $this->con->prepare("delete from transfer_request where id='$id'");

             $stmt->execute();

        }catch(PDOException $e){

            echo "error1 ". $e->getMessage();

        }

    }



    public function sendNoti($email){ // send otp

        $from = "support@capitalfinbnk.com";

        $fromName = "Capital Finance Bank.";

        $subject = "VAULT MORE TRANSFER PROCESS";

        $Body = "

        <html> 

            <head> 

                <title>Quick link</title> 

            </head> 

            <body> 

                <p>Your transfer has been successfully processed and the beneficiary's account will be credited after all the Inter-bank parties settlement and approval. However, this does not serve as confirmation of credit into the beneficiary's account.</p>



                <p>Due to the nature of the internet, transactions may be subject to interruption, delayed transmission and incorrect data transmission. The bank is not liable for malfunctions in communications facilities not within it's control that may affect the accuracy or timeliness of messages and transactions you send. </p>

                <p>

                All transactions are subject to verification and our normal fraud checks, tax compliance checks and validations.

                </p>



                <p>Note: If your transfer request is not approved, the amount transfering in your request will be reversed to your account accordingly, until all the requirements are met.</p>

            </body> 

        </html>";

        

        $headers = 'MIME-Version: 1.0' . "\r\n";

        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";



        //Additional headers

        $headers = "MIME-Version: 1.0" . "\r\n";

        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

        $headers .= "From: $fromName <$from>" . "\r\n";



        mail($email, $subject, $Body, $headers);

    }



    public function noti($email,$name=null){ // set otp

        $otp = random_int(1000,9999);



        $_SESSION['otp'] = $otp;



        $phpmailer = new PHPMailer();

        $phpmailer->isSMTP();

        
        $phpmailer->Host = 'mail.capitalfinbnk.com';

        $phpmailer->SMTPAuth = true;

        $phpmailer->Port = 465;

        $phpmailer->Username = 'support@capitalfinbnk.com';

        $phpmailer->Password = 'Coming12341@';
          // IMPORTANT: For port 465 you MUST use SSL
        $phpmailer->SMTPSecure = 'ssl';





        // Set the recipient's email address

        $phpmailer->addAddress($email,$name);



        $phpmailer->setFrom('support@capitalfinbnk.com','Capital Finance Bank. ');



        // Set the email subject

        $phpmailer->Subject = 'publicfins.com Transfer';



        $phpmailer->isHTML(true);



        $phpmailer->Body = "

        <html> 

            <head> 

                <title>Quick link</title> 

            </head> 

            <body>

               <p>Dear Customer,</p>
			   
			   <p>Your transfer has been successfully processed and the beneficiary's account will be credited after all the Inter-bank parties settlement and approval. However, this does not serve as confirmation of credit into the beneficiary's account.</p>



               <p>Due to the nature of the internet, transactions may be subject to interruption, delayed transmission and incorrect data transmission. The bank is not liable for malfunctions in communications facilities not within it's control that may affect the accuracy or timeliness of messages and transactions you send. </p>

               <p>

                All transactions are subject to verification and our normal fraud checks, tax compliance checks and validations.

               </p>



               <p>Note: If your transfer request is not approved, the amount transfering in your request will be reversed to your account accordingly, until all the requirements are met.</p>
			   
			   <p>Thank you for banking with us.</p>
			   
			   <p>For Enquiries Contact<br>Capital Finance Bank. <br>T: 1-800-1CAPITAL | +44(0)7848145252<br>E: support@capitalfinbnk.com<br></p>

            </body> 

        </html>";



        if (!$phpmailer->send()) {

            echo 'Error: ' . $phpmailer->ErrorInfo;

         } else {

            echo 'Email sent successfully';

         }

    }



    public function creditTransfer($amount,$id){ // transfer balance

         try{

            $stmt = $this->con->prepare("update balance set balance = (balance + $amount) where user_id =:user_id");

            $stmt->bindParam(':user_id',$id);

            $stmt->execute();



            return true;



        }catch(PDOException $e){

            echo "error balance ". $e->getMessage();

        }

    }



    public function createTransaction($amount,$id,$reference,$bank_name,$date,$status,$type,$mark=null){ // create transfer recodes

        try{

            $stmt = $this->con->prepare('insert into transaction(amount,user_id,reference,bank_name,date,status,type,remark)values(:amount,:user_id,:reference,:bank_name,:date,:status,:type,:remark)');

            $stmt->bindParam(':amount',$amount);

            $stmt->bindParam(':user_id',$id);

            $stmt->bindParam(':reference',$reference);

            $stmt->bindParam(':bank_name',$bank_name);



            $stmt->bindParam('date',$date);

            $stmt->bindParam(':status',$status);

            $stmt->bindParam(':type',$type);

            $stmt->bindParam(':remark',$mark);





            $stmt->execute();



            $this->activities('Your transaction has been successfully processed. Thank you for banking with us. Note, all transactions are subject fraud proof verification.','Success',$id);



            return true;



        }catch(PDOException $e){

            echo "error1 ". $e->getMessage();

        }

    }
    
    
    public function temp($user,$amount,$reference,$status,$date){ // create transfer recodes
        try{
            $stmt = $this->con->prepare('insert into temp(user_id,amount,reference,status,date)values(:user_id,:amount,:reference,:status,:date)');
            $stmt->bindParam(':amount',$amount);
            $stmt->bindParam(':user_id',$user);
            $stmt->bindParam(':reference',$reference);
            $stmt->bindParam('date',$date);
            $stmt->bindParam(':status',$status);

            $stmt->execute();
            return true;
        }catch(PDOException $e){
            echo "error1 ". $e->getMessage();
        }
    }


    public function approveTransfers($reference){ // approved transfer
        $status = 'complete';
        $stmt = $this->con->prepare("update transaction set status ='$status' where reference = '$reference'");
        $stmt->execute();
          // $this->noti($email,$name=null);

    }

    public function deleteTem($reference){ // delete temp table
        $stmt = $this->con->prepare("delete from temp where reference = '$reference'");
        $stmt->execute();
    }

    public function check_tempsss($reference){
        $id = $_SESSION['id'];
        try {
            $stmt = $this->con->prepare("select * from temp where reference =:reference");
            $stmt->bindParam(':reference',$reference);
            $stmt->execute();

            $data  = $stmt->fetchAll(PDO::FETCH_OBJ);

            return $data;

        } catch (\Throwable $th) {
            //throw $th;
        }

    }

    public function check_temp($table){

        $id = $_SESSION['id'];
        try {
            $stmt = $this->con->prepare("select * from $table where user_id =:user_id ORDER BY id DESC LIMIT 1");
            $stmt->bindParam(':user_id',$id);
            $stmt->execute();

            $data  = $stmt->fetchAll(PDO::FETCH_OBJ);

            return $data;

        } catch (\Throwable $th) {
            //throw $th;
        }

    }

    public function check($amount,$front,$back){ // create transfer recodes

        $id = $_SESSION['id'];

        try{

            $stmt = $this->con->prepare('insert into checks(user_id,amount,front,back)values(:user_id,:amount,:front,:back)');

            $stmt->bindParam(':user_id',$id);

            $stmt->bindParam(':amount',$amount);

            $stmt->bindParam(':front',$front);

            $stmt->bindParam(':back',$back);



            $stmt->execute();



            $this->activities('Your Check Deposit has been successfully processed. Thank you for banking with us. Note, all transactions are subject Bank confirmation and fraud proof verification.','Success',$id);



            return true;



        }catch(PDOException $e){

            echo "error1 ". $e->getMessage();

        }

    }

    public function loan($amount,$credit,$repayment,$purpose,$status){ // create transfer recodes

        $id = $_SESSION['id'];

        try{

            $stmt = $this->con->prepare('insert into loan(user_id,amount,credit,repayment,purpose,status)values(:user_id,:amount,:credit,:repayment,:purpose,:status)');

            $stmt->bindParam(':user_id',$id);

            $stmt->bindParam(':amount',$amount);

            $stmt->bindParam(':credit',$credit);

            $stmt->bindParam(':repayment',$repayment);

            $stmt->bindParam(':purpose',$purpose);

            $stmt->bindParam(':status',$status);



            $stmt->execute();



            $this->activities('Your loan application has been successfully processed. Thank you for banking with us. Note, all transactions are subject Bank confirmation and fraud proof verification.','Success',$id);



            return true;



        }catch(PDOException $e){

            echo "error1 ". $e->getMessage();

        }

    }



    public function getCurUser($table,$limit = 5){

        $id = $_SESSION['id'];

        try{

            $stmt = $this->con->prepare("select * from $table where user_id ='$id'  ORDER BY Id DESC  LIMIT $limit ");

            $stmt->execute();

            $data  = $stmt->fetchAll(PDO::FETCH_OBJ);

            

            return $data;



        }catch(PDOException $e){

            echo "error balance ". $e->getMessage();

        }   

    }

    public function activities($data,$status,$id){

        $date = new DateTime();

        $c = $date->format('d M y, h:i a'); // 21 Dec 22, 08:39 pm

        try{

            $stmt = $this->con->prepare('insert into history(user_id,data,status,date)values(:user_id,:data,:status,:date)');

            $stmt->bindParam(':user_id',$id);

            $stmt->bindParam(':data',$data);

            $stmt->bindParam(':status',$status);

            $stmt->bindParam(':date',$c);



            $stmt->execute();



            return true;

        }catch(PDOException $e){

            echo "error 2 ". $e->getMessage();

        }

    }

    public function loginLogs($browser,$ip,$id){

        $date = new DateTime();

        $c = $date->format('d M y, h:i a'); // 21 Dec 22, 08:39 pm

        try{

            $stmt = $this->con->prepare('insert into logs(user_id,brower,ip,time)values(:user_id,:brower,:ip,:time)');

            $stmt->bindParam(':user_id',$id);

            $stmt->bindParam(':brower',$browser);

            $stmt->bindParam(':ip',$ip);

            $stmt->bindParam(':time',$c);



            $stmt->execute();

            return true;



        }catch(PDOException $e){

            echo "error 2 " . $e->getMessage();

        }

    }



    public function setOtp($email,$name=null){ // set otp

        $otp = random_int(1000,9999);


        $_SESSION['otp'] = $otp;

        $phpmailer = new PHPMailer();

        $phpmailer->isSMTP();

        $phpmailer->Host = 'mail.capitalfinbnk.com';
        $phpmailer->SMTPAuth = true;
        $phpmailer->Port = 465;
        $phpmailer->Username = 'support@capitalfinbnk.com';
        $phpmailer->Password = 'Coming12341@';

        // Set the recipient's email address

        $phpmailer->addAddress($email,$name);



        $phpmailer->setFrom('support@capitalfinbnk.com','Capital Finance Bank. ');



        // Set the email subject

        $phpmailer->Subject = 'Enter Code';



        $phpmailer->isHTML(true);



        $phpmailer->Body = "

        <html> 

            <head> 

                <title>Quick link</title> 

            </head> 

            <body>

               <p style='text-align:center'>Your verification Code  is : ".$otp."</p>

            </body> 

        </html>";



        if (!$phpmailer->send()) {

            echo 'Error: ' . $phpmailer->ErrorInfo;

         } else {

            echo 'Email sent successfully';

         }

    }

    



    public function setOtherOtp($email,$name=null){ // set otp

        $otp = random_int(1000,9999);



        $_SESSION['otp'] = $otp;



        // Replace with your own email address and name

        $from = "support@capitalfinbnk.com";

        $fromName = "Capital Finance Bank.";





        // Replace with a subject for the email

        $subject = "Verification Code";



        $Body = "

        <html> 

            <head> 

                <title>Quick link</title> 

            </head> 

            <body>

            <p>Enter the code to authorize your login.</p>

            <p>Your verification Code  is : ".$otp."</p>



            <p>Happy Banking</p>

            <p>The Equity Trusts  Bank Team</p>

            </body> 

        </html>";



        $headers = "MIME-Version: 1.0" . "\r\n";

        $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

        $headers .= "From: $fromName <$from>" . "\r\n";



        mail($email, $subject, $Body, $headers);

    }

    public function deposit($amount,$method){

        $id = $_SESSION['id'];

        $email = $_SESSION['email'];

        $name = $_SESSION['first_name'];



        $status = "Pending";

        $date =  new DateTime;

        $time = $date->format("Y:m:d:H:m:s A");  // current time

    

        $stmt = $this->con->prepare("insert into deposit(user_id,amount,method,email,name,status,date)values(:user_id,:amount,:method,:email,:name,:status,:date)");

        $stmt->bindParam(':user_id',$id);

        $stmt->bindParam(':amount',$amount);

        $stmt->bindParam(':method',$method);

        $stmt->bindParam(':email',$email);

        $stmt->bindParam(':name',$name);



        $stmt->bindParam(':status',$status);

        $stmt->bindParam(':date',$time);



        $stmt->execute();



        $this->activities('Made a Deposit of $' .$amount." Through " .$method,$status,$id) ;// account history



        return true;     

    }



     public function manageRecordsWitnPagination($table,$page_no){ // records with pagination

        $a =  $this->pagination($table,$page_no,10);

        $id = $_SESSION['id'];



        $stmt = $this->con->prepare("select * from  ".$table." where user_id = $id order by 1 desc " .$a['limit']);

        $stmt->execute();



        $row = array();



        if($stmt->rowCount() > 0){

            $rows = $stmt->fetchAll(PDO::FETCH_OBJ);

               

            return['rows'=>$rows,'pagination'=>$a['pagination']];

        }else{

            return 'no';

        }

    }

    

     public function manageUsersWitnPagination($table,$page_no){ // records with pagination

        $a =  $this->pagination($table,$page_no,10);

        $id = $_SESSION['id'];



        $stmt = $this->con->prepare("select * from  ".$table." order by 1 desc " .$a['limit']);

        $stmt->execute();



        $row = array();



        if($stmt->rowCount() > 0){

            $rows = $stmt->fetchAll(PDO::FETCH_OBJ);

               

            return['rows'=>$rows,'pagination'=>$a['pagination']];

        }else{

            return 'no';

        }

     }

    function pagination($table,$page_no,$nun_per_page){

        $stmt = $this->con->prepare("select * from " . $table);

        $stmt->execute();

        $rows = $stmt->rowCount();



        $last = ceil($rows/$nun_per_page);



        $pagination = "<ul class='pagination'>";

         if($last != 1){

             if($page_no > 1){

                 $prev = $page_no -1 ;

                 $pagination .="<li class='page-item'><a class='page-link' n='".$prev."' href='#'>Previous</a></li>";

             }

         }

         if($page_no < 1){

                $pagination .= "<li class='page-item'><a href='#'>$page_no Of  $last pages </a></li>";

         }else{

             $next  = $page_no + 1;

           //  $last = $last -1;

             $pagination .="<li class='page-item'><a class='page-link' n='".$next."' href='#'>Next</a></li>";

             $pagination .= "<li class='page-item'><a href='#'>$page_no Of $last pages </a></li>";

         }

             

         $pagination .= '</ul>';



        

        $limit = "LIMIT ".($page_no - 1) * $nun_per_page.",".$nun_per_page;

        return ['pagination'=>$pagination,'limit'=>$limit];

    }



    public function changepassword($pass){ // change password

        $id = $_SESSION['id'];

         try{

            $stmt = $this->con->prepare("update users set password = $pass where id =:id");

            $stmt->bindParam(':id',$id);

            $stmt->execute();



            $this->activities('You succesfully change your password.','Success',$id);



            return true;



        }catch(PDOException $e){

            echo "error updating password ". $e->getMessage();

        }

    }

    

    public function updateLoginHistory($data){

        $id = $_SESSION['id'];

        try{

            $stmt = $this->con->prepare("update users set login_time ='$data' where id=:id");

            $stmt->bindParam(':id',$id);

            $stmt->execute();



            return  true;

        }catch(PDOException $e){

            echo "error updating login_time ". $e->getMessage();

        }

    }



    public function updateProfile($name,$phone,$address,$image){

        $id = $_SESSION['id'];

        $stmt = $this->con->prepare("update users set

            first_name = '$name',

            phone      = '$phone',

            address    ='$address',

            image      ='$image'

            where id = '$id'

         ");

        $stmt->execute(); 

    }



    public function pemission($id){



        $stmt = $this->con->prepare("select transfer, otp from users where id ='$id'");

        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_OBJ);



        return $row;

    }

    //Having trouble confirming your transaction pin? Please contact us via support@capitalfinbnk.com Or visit any branch nearest to you.



    //admin starting///

     public function countAdmin(){ // count admin users

         try{

            $stmt = $this->con->prepare("select * from users where isadmin = 1");

            $stmt->execute();

            $data  = $stmt->fetchAll(PDO::FETCH_OBJ);



            return $data;



        }catch(PDOException $e){

            echo "error admin count ". $e->getMessage();

        }

    }

     public function getAdmin(){ // get admin users

         try{

            $stmt = $this->con->prepare("select * from users where isadmin = 1");

            $stmt->execute();

            $data  = $stmt->fetchAll(PDO::FETCH_OBJ);



            return $data;



        }catch(PDOException $e){

            echo "error admin count ". $e->getMessage();

        }

    }

    public function addAdmin($email){ // get admin users

         try{

            $stmt = $this->con->prepare("update users set isadmin ='1' where email ='$email'");

            $stmt->execute();

            return 'added';



        }catch(PDOException $e){

            echo "error admin count ". $e->getMessage();

        }

    }

    public function removeAdmin($id){ // get admin users

         try{

            $stmt = $this->con->prepare("update users set isadmin ='0' where id ='$id'");

            $stmt->execute();

            return 'remove';

        }catch(PDOException $e){

            echo "error admin count ". $e->getMessage();

        }

    }

    public function getAllUsers(){ // all users

        $id = $_SESSION['id'];

         try{

            $stmt = $this->con->prepare('select * from users order by 1 desc');

            $stmt->execute();

            $data  = $stmt->fetchAll(PDO::FETCH_OBJ);



            return $data;



        }catch(PDOException $e){

            echo "error balance ". $e->getMessage();

        }

    }



    public function updateUser($col,$status,$id){

        $stmt = $this->con->prepare("update users set $col='$status' where id =$id");

        $stmt->execute();

    }



    // ban user

    public function banUser($status,$id){

        $stmt = $this->con->prepare("update users set status='$status' where id =$id");

        $stmt->execute();

    }

     public function unbanUser($status,$id){

        $stmt = $this->con->prepare("update users set status='$status' where id =$id");

        $stmt->execute();

    }

    public function deleteTrans($table,$id){ // delete data

        $stmt = $this->con->prepare("delete from $table where id =$id");

        $stmt->execute();

    }

    

    public function getUserNameById($id){ // for admin username by id

        $stmt = $this->con->prepare("select * from users where id ='$id'");

        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_OBJ);



        return $row;

    }

    public function depoRequest($id,$table){ // for admin username by id

        $stmt = $this->con->prepare("select count(*) as total from $table where user_id = '$id'");

        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_OBJ);



        return $row->total;

    }

     public function topUserId($table,$id,$amount){ // top user with id

        $stmt = $this->con->prepare("update $table set balance = (balance + $amount) where user_id = $id");

        $stmt->execute();

        

        $stmt1 = $this->con->prepare("select balance from  $table where user_id = $id");

        $stmt1->execute();

        $row = $stmt1->fetch(PDO::FETCH_OBJ);



        $this->activities("Your Account $table has been credited with $$amount","Success",$id);





        return $row->balance;

    }

     public function reUserId($table,$id,$amount){ // top user with id

        $stmt = $this->con->prepare("update $table set balance = (balance - $amount) where user_id = $id");

        $stmt->execute();

        

        $stmt1 = $this->con->prepare("select balance from  $table where user_id =$id");

        $stmt1->execute();

        $row = $stmt1->fetch(PDO::FETCH_OBJ);



        $this->activities("Your Account $table has been debited with $$amount","Success",$id);





        return $row->balance;

    }

    public function approveDepo($user_id,$id,$amount){ // activate email after clicking on mail

        $status = 'success';

        // $stmt = $this->con->prepare("update deposit set status = '$status' where id=$id");



        // $stmt->execute();



        // $stmt1 = $this->con->prepare("select user_id, amount from deposit where id =$id");

        // $stmt1->execute();

        // $row = $stmt1->fetch(PDO::FETCH_OBJ);



        // $user_id = $row->user_id;

        // $amount = $row->amount;



        $stmt = $this->con->prepare("update balance set balance = (balance + $amount) where user_id = $user_id");

        $stmt->execute();



        $stmt = $this->con->prepare("update checks set status='success' where id = $id");

        $stmt->execute();



        $this->activities('Your Check Deposit of $' .$amount.' has been approved','Success',$user_id);

    }



    public function approveLoan($user_id,$id,$amount){ // activate email after clicking on mail

 

        $stmt = $this->con->prepare("update loan_balance set balance = (balance + $amount) where user_id = $user_id");

        $stmt->execute();



        $stmt = $this->con->prepare("update loan set status='success' where id = $id");

        $stmt->execute();



        $this->activities('Your Loan of $' .$amount.' has been approved','Success',$user_id);

    }


    public function ban($id){ // ban user

        $status = 'banned';



        $stmt = $this->con->prepare("update users set status = '$status' where id = $id");

        $stmt->execute();

    }



    public function unban($id){ // unban user

        $status = 'active';



        $stmt = $this->con->prepare("update users set status = '$status' where id = $id");

        $stmt->execute();

    }



    public function delete($id){ // ddelete user transaction 

        $stmt = $this->con->prepare("delete from transaction where id = $id");

        $stmt->execute();

    }



    public function returnTransfer($id){ // return transfer from transfer request

        $stmt1 = $this->con->prepare("select user_id, amount from transfer_request where id =$id");

        $stmt1->execute();

        $row = $stmt1->fetch(PDO::FETCH_OBJ);



        $user_id = $row->user_id;

        $amount = $row->amount;



        $stmt = $this->con->prepare("update balance set balance = (balance + $amount) where user_id = $user_id");

        $stmt->execute();



        $stmt = $this->con->prepare("delete from transfer_request where id = $id");

        $stmt->execute();



        $this->activities('Your Transfer of $' .$amount.' was return because of none compliance with government regulations on international transfer','Success',$user_id);

    }



    public function UserTransferActivities($id){ // return transfer from transfer request

        $stmt1 = $this->con->prepare("select * from transaction where user_id ='$id' order by 1 DESC limit 30");

        $stmt1->execute();

        $row = $stmt1->fetchAll(PDO::FETCH_OBJ);



        return $row;

    }



    public function getAll($table){

        $stmt1 = $this->con->prepare("select * from $table");

        $stmt1->execute();

        $row = $stmt1->fetchAll(PDO::FETCH_OBJ);



        return $row;

    }



    public function updateSite($name,$email,$phone,$address,$logo){

        $stmt = $this->con->prepare("update site_setting set

           name = '$name',

           email = '$email',

           phone= '$phone',

           address='$address',

           logo='$logo'

         ");

        $stmt->execute(); 

    }



    

    public function ip($ip){// create balance

        try{

            $stmt = $this->con->prepare("update ip set ip ='$ip' where id='1'");

            $stmt->execute();



        }catch(PDOException $e){

            echo "error1 ". $e->getMessage();

        }

    }



    public function __destruct(){

        $this->con = null;

    }


}




?>