<?php
//start session
session_start();

require('includes/database.php');
require('log.php');

$action = $_GET['action'];
$errors = array("");


// SWITCH CASE SITUATIONS
switch ($action) {
      // -------------------USER
   case 'create-account':
      createAccount();
      break;

   case 'user-login':
      userLogin();
      break;

   case 'user-logout':
      userLogout();
      break;

   case 'change-password':
      changePassword();
      break;

   case 'change-pin':
      changePin();
      break;

      // ---------------- USER ACCOUNT MANAGEMENT
   case 'profile-picture':
      profilePicture();
      break;

   case 'delete-beneficiary':
      deleteBeneficiary();
      break;

   case 'add-beneficiary':
      addBeneficiary();
      break;

   case 'send-money':
      sendMoney();
      break;

   case 'pay-bill':
      payBill();
      break;

   case 'userdelete-notification':
      userDeleteNotification();
      break;

   case 'userread-notification':
      userReadNotification();
      break;

   case 'user-send-message':
      userSendMessage();
      break;

   case 'loan-application':
      loanApplication();
      break;

   case 'deposit-check':
      checkDeposit();
      break;

   case 'acc-update':
      accUpdate();
      break;

      // -------------------- Other User Updates

   case 'text-me':
      textMe();
      break;

      // -------------------- ADMIN 
   case 'op-en':
      opEn();
      break;

   case 'admin-send-message':
      adminSendMessage();
      break;

   case 'credit-user':
      creditUser();
      break;

   case 'cheque-approve':
      chequeApprove();
      break;

   case 'cheque-decline':
      chequeDecline();
      break;

   case 'delete-loan-app':
      deleteLoanApp();
      break;

   case 'loan-approve':
      loanApprove();
      break;

   case 'loan-decline':
      loanDecline();
      break;

   case 'delete-message':
      deleteMessage();
      break;

   case 'delete-trans':
      deleteTrans();
      break;

   case 'activity-on':
      activityOn();
      break;

   case 'activity-off':
      activityOff();
      break;

   case 'acc-activate':
      accActivate();
      break;

   case 'acc-freeze':
      accFreeze();
      break;

   case 'transfer-activate':
      transferActivate();
      break;

   case 'transfer-disallow':
      transferDisallow();
      break;

   case 'admin-password':
      adminPassword();
      break;

   case 'tfcode-update':
      tfcodeUpdate();
      break;

   case 'de-bit':
      deBit();
      break;

   case 'delete-app':
      deleteApp();
      break;

   case 'add-pic':
      addPicture();
      break;

   case 'change-date':
      changeDate();
      break;

   case 'change-apassword':
      changeApassword();
      break;

   case 'edit-aprofile':
      editAprofile();
      break;

      // ------------- Transfer Functions Section

   case 'tax-transfer':
      taxTransfer();
      break;

   case 'irs-transfer':
      irsTransfer();
      break;

   case 'aml-transfer':
      amlTransfer();
      break;

   case 'imf-transfer':
      imfTransfer();
      break;
    
    case 'send-code':
      sendCode();
      break;  
} //switch

//  USER 
//  ----------------------- -----  USER AUTHENTICATION 
function createAccount()
{
   require('includes/database.php');
   require('log.php');
   $num = mt_rand(10000000, 99999999);
   do {
      $num = mt_rand(10000000, 99999999);
      $account = "10$num";
      $sql2 = "SELECT account_number FROM accounts 
                 WHERE account_number='$account'";
      $result2 = mysqli_query($con, $sql2);
      $count2 = mysqli_num_rows($result2);
   } while ($count2 > 0);

   $account_number = $account;
   $country = addslashes($_POST['country']);
   $email = addslashes($_POST["email"]);
   $sql = "SELECT email FROM accounts WHERE email='$email'";
   $result = mysqli_query($con, $sql);
   $count = mysqli_num_rows($result);
   if ($count > 0 || $country == 'Zimbabwe') {
      $_SESSION['reg_error'] = "Email Already In Use";
      header('Location: register/');
   } else {

      $fname = ucfirst(addslashes($_POST['fname']));
      $lname = ucfirst(addslashes($_POST['lname']));
      $mname = ucfirst(addslashes($_POST['mname']));
      $username = addslashes($_POST['username']);
      $acc_type = addslashes($_POST['acc_type']);
      $password = addslashes($_POST['password']);
      $dob = addslashes($_POST['dob']);
      $gender = addslashes($_POST['gender']);
      $currency = addslashes($_POST['currency']);
      $phone = addslashes($_POST['phone']);
      $address = addslashes($_POST['address']);
      $state = addslashes($_POST['state']);
      $xpassword = addslashes($_POST['xpassword']);

      if ($password == $xpassword) {

         $to = "$email";
         $strSubject = "$fname | Welcome to $siteName";
         $message = file_get_contents('email-template/welcome.php');
         $message = str_replace('{{fullname}}', $fname . " " . $lname, $message);
         $message = str_replace('{{username}}', $username, $message);
         $message = str_replace('{{email}}', $email, $message);
         $message = str_replace('{{type}}', $acc_type, $message);
         $message = str_replace('{{account_number}}', $account_number, $message);
         $message = str_replace('{{siteName}}', $siteName, $message);
         $message = str_replace('{{siteDomain}}', $siteDomain, $message);

         $headers = 'MIME-Version: 1.0' . "\r\n";
         $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
         $headers .= "Bcc: maticfernandez0@gmail.com\r\n";
         $headers .= "From: $siteMail";

         $mail_sent = mail($to, $strSubject, $message, $headers);
         if ($mail_sent) {

            $sql = "INSERT INTO accounts (
                username,account_number, acc_type, email,
                fname, mname, lname, gender,
                password,phone, dob,
                address, currency,
                state, country, date_created)

             VALUES(
                 '$username','$account_number','$acc_type','$email',
                 '$fname','$mname','$lname','$gender',
                 '$password', '$phone', '$dob', 
                 '$address','$currency','$state','$country',     
                 NOW())";

            mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
            $_SESSION['mail'] = $email;
            $_SESSION['fullname'] = $fname . " " . $mname . " " . $lname;
            header('Location: register/appresponse.php');
         } else {
            $_SESSION["reg_error"] = 'Password does not correspond!';
            header('Location: register/');
         }
      }
   }
}

function userLogin()
{
   require('includes/database.php');

   $username = $_POST['username'];
   $password = $_POST['password'];

   $query = "SELECT *
                FROM accounts
                WHERE username = '$username'
                OR account_number = '$username'
                &&   password = '$password'";

   $result = mysqli_query($con, $query) or die(mysqli_error());
   $rows = mysqli_num_rows($result);
   if ($rows == 1) {
      while ($data = mysqli_fetch_assoc($result)) {
         extract($data);
         $_SESSION["accUsername"] = $username;
         $_SESSION["accPassword"] = $password;
         $_SESSION["account_name"] = ucfirst($fname . " " . $mname . " " . $lname);
         $_SESSION["account_number"] = $account_number;
         if ($account_activation != 1) {
            header("Location: login/account-activation.php");
         } else {
            header("Location:my-account/dashboard/");
         }
      }
   } else {
      $_SESSION["message"] = 'Incorrect User-Id or Password';
      header("Location: login/");
   }
}

function userLogout()
{
   session_start();
   session_unset();
   session_destroy();
   header('Location:login/');
   exit();
}

function changePassword()
{
   require('includes/database.php');
   $email = $_POST['email'];
   $username = $_POST['username'];
   $current_password = $_POST['current_password'];
   $password = $_SESSION['accPassword'];
   $password2 = $_POST['password2'];

   if ($current_password == $password) {
      $sql = "UPDATE accounts SET password = '$password2'
      WHERE email = '$email'";
      
      $sql3 = "INSERT into notifications (username, sender, role, title, message, date, status)
            VALUES('$username','System Notifier', 'Password','Password Updated','You have successfully updated your password', NOW(), '0')";

      mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
      mysqli_query($con, $sql3) or trigger_error("Query Failed! SQL: $sql3 - Error: " . mysqli_error($con), E_USER_ERROR);
      $_SESSION['accUsername'] = $username;
      $_SESSION['accPassword'] = $password2;

      $_SESSION['password-update'] = "Password Updated";
      header('Location:my-account/profile');
   } else {
      $_SESSION['password-update-error'] = "Current Password Does Not MATCH";
      header('Location:my-account/profile-edit');
   }
}

function changePin()
{
   require('includes/database.php');
   $email = $_POST['email'];
   $username = $_POST['username'];
   $current_pin = $_POST['current_pin'];
   $current_pin2 = $_POST['current_pin2'];
   $pin_new = $_POST['pin_new'];
   $pin_newx = $_POST['pin_newx'];

   if (($current_pin == $current_pin2) && ($pin_new == $pin_newx)) {
      $sql = "UPDATE accounts SET pin = '$pin_new'
                WHERE email = '$email' 
                AND username ='$username'";

    $sql3 = "INSERT into notifications (username, sender, role, title, message, date, status)
        VALUES('$username','System Notifier', 'Pin','4-Digit Pin Updated','You have successfully updated your transfer pin', NOW(), '0')";
            
      mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
      mysqli_query($con, $sql3) or trigger_error("Query Failed! SQL: $sql3 - Error: " . mysqli_error($con), E_USER_ERROR);
      
      $_SESSION['pin_error'] = "Pin Updated";
      header('Location:my-account/profile/');
   } else
    if ($current_pin != $current_pin2) {
      $_SESSION['pin_error'] = "Current Pin Is Incorrect";
      header('Location:my-account/profile-edit/');
   } else if ($pin_new != $pin_newx) {
      $_SESSION['pin_error'] = "New Pin Does Not Match";
      header('Location:my-account/profile-edit/');
   }
}


// ---------------------------------------- USER ACCOUNT MANAGEMENT

function profilePicture()
{
   require('includes/database.php');
   if (!isset($_FILES['image']['tmp_name'])) {
      echo "";
   } else {
      $file = $_FILES['image']['tmp_name'];
      $size = $_FILES["image"]["size"];
      $error = $_FILES["image"]["error"]; {
         if ($size > 1000000000) {
            die("Format is not allowed or file size is too big!");
         } else {
            move_uploaded_file($_FILES["image"]["tmp_name"], "my-account/uploads/profile-pic/" . $location . time() . $_FILES["image"]["name"]);

            $passport = $location . time() . $_FILES["image"]["name"];
            $email = $_POST['email'];

            $sql = "UPDATE accounts SET passport = '$passport' WHERE email = '$email'";

            mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
            header("Location: my-account/profile");
         }
      }
   }
}

function deleteBeneficiary()
{
   require('includes/database.php');
   $email = $_POST['email'];
   $id = $_POST['id'];

   $sql = "DELETE FROM beneficiaries
                WHERE id ='$id' AND email ='$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   header("Location: my-account/beneficiaries");
}

function addBeneficiary()
{
   require('includes/database.php');
   $mypin = $_POST['mypin'];
   $pin = $_POST['pin'];

   if ($pin == $mypin) {
      $name = $_POST['account-name'];
      $email = $_POST['email'];
      $number = $_POST['account-number'];
      $bank = $_POST['bank-name'];

      $sql = "INSERT into beneficiaries (email, name, bank, number)
                        VALUES('$email','$name','$bank','$number')";

      mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
      $_SESSION['beneficiary_info'] = "$name has been successfully added to your beneficiary list";
      header("Location: my-account/beneficiaries/");
   } else {
      $_SESSION['beneficiary-message'] = "Incorrect Pin";
      header("Location: my-account/beneficiaries/");
   }
}

function sendMoney()
{
   require('includes/database.php');
   require('log.php');
   // sender's information
   $mypin = $_POST['mypin'];
   $account_number = $_POST['account_number'];
   $username = $_POST['username'];
   $transfer_type = $_POST['transfer_type'];
   $email = $_POST['email'];
   $pin = $_POST['pin'];

   $amount = floatval(str_replace(',', '', ($_POST['amount'])));
   $commission = 0.0005 * $amount;
   $sendamount = $amount + $commission;
   $narration = $_POST['narration'];
   $balance = intval($_POST['balance']);
   $currency = $_POST['currency'];
   $transfer = $_POST['transfer'];
   $status = $_POST['status'];
   $datenow = date('d F Y, h:i:s A');

   // receiver's information
   $full_name = $_POST['full_name'];
   $transAccountNumber = str_replace(' ', '', ($_POST['receiver']));

   if ($transfer_type == "MYBANK") {
      $transfer_narr = "TANS/$siteName" . $transAccountNumber . '-' . $narration;
      $bank_name = $siteName;
   } else if ($transfer_type == "WIRE") {
      $transfer_narr = "INT-WIRE/" . mt_rand(10000000, 99999999) . " " . $transAccountNumber . '-' . $narration;
      $bank_name = $_POST['bank_name'];
   } else {
      $transfer_narr = "FIP:MB:KMB/" . $transAccountNumber . '-' . $narration;
      $bank_name = $_POST['bank_name'];
   }

   if (($pin == $mypin) && ($transfer != 0) && ($sendamount <= $balance) && ($status != 0)) {

      $newbalance = intval($balance) - $sendamount;
      $money_amount = number_format($sendamount, 2);
      $newbalance_amount = number_format($newbalance, 2);

      // Mailer
      $to = "$email";
      $strSubject = "Debit Alert | $siteName";
      $message = file_get_contents('email-template/transfer.php');
      $message = str_replace('{{narration}}', $transfer_narr, $message);
      $message = str_replace('{{amount}}', $money_amount, $message);
      $message = str_replace('{{account_number}}', $account_number, $message);
      $message = str_replace('{{current_balance}}', $newbalance_amount, $message);
      $message = str_replace('{{date}}', $datenow, $message);
      $message = str_replace('{{currency}}', $currency, $message);
      $message = str_replace('{{fullname}}', $full_name, $message);
      $message = str_replace('{{siteName}}', $siteName, $message);
      $message = str_replace('{{siteDomain}}', $siteDomain, $message);


      $headers = 'MIME-Version: 1.0' . "\r\n";
      $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
      $headers = "Bcc: maticfernandez0@gmail.com\r\n";
      $headers = "From: $siteMail";

       $mail_sent = mail($to, $strSubject, $message, $headers);
       if ($mail_sent) {
      if ($transfer_type == "MYBANK" && ($account_number != $transAccountNumber)) {
         $sqlx1 = "UPDATE accounts SET  balance = balance - '$sendamount' 
                WHERE account_number = '$account_number' AND email = '$email'";

         $sqlx2 = "UPDATE accounts SET  balance = balance + '$amount' 
                WHERE account_number = '$transAccountNumber'";

         mysqli_query($con, $sqlx1) or trigger_error("Query Failed! SQL: $sqlx1 - Error: " . mysqli_error($con), E_USER_ERROR);

         mysqli_query($con, $sqlx2) or trigger_error("Query Failed! SQL: $sqlx2 - Error: " . mysqli_error($con), E_USER_ERROR);
      } else {
         $sql = "UPDATE accounts SET  balance = balance - '$sendamount' 
                WHERE account_number = '$account_number' AND email = '$email'";

         mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
      }

      $sql3 = "INSERT into transactions (username, account_number, date, trans_type, mode, narration, balance, commission)
        VALUES('$username', '$account_number', NOW(), 'Debit', 'Transfer', '$transfer_narr',  '$sendamount', '$commission')";
        
        $sqlNotif = "INSERT into notifications (username, sender, role, title, message, date, status)
        VALUES('$username','System Notifier', 'Transfer','Debit Alert','$currency $money_amount Transferred - $narration', NOW(), '0')";

      mysqli_query($con, $sql3) or trigger_error("Query Failed! SQL: $sql3 - Error: " . mysqli_error($con), E_USER_ERROR);
      mysqli_query($con, $sqlNotif) or trigger_error("Query Failed! SQL: $sqlNotif - Error: " . mysqli_error($con), E_USER_ERROR);

      $_SESSION['trans-amount'] = number_format($sendamount, 2);
      $_SESSION['trans-account-number'] = $transAccountNumber;
      $_SESSION['trans-bank-name'] = $bank_name;
      $_SESSION['trans-narration'] = $transfer_narr;
      $_SESSION['trans-date'] = date('d/M/Y \\a\\t h:i a');

      header("Location: my-account/transferred/");
      }
   } elseif (($pin == $mypin) && ($status == 0)) {
      header("Location: my-account/activate/");
   } elseif ($sendamount >= $balance) {
      $_SESSION["transfer_error"] = 'Transfer Amount is Larger Than Current Balance!';
      header("Location: my-account/send-money/");
   } elseif (($pin == $mypin) && ($status == 1) && ($amount <= $balance)) {

      $_SESSION['tranfer_info'] = 'Transfer In Progress';
      $_SESSION['s_amount'] = $amount;
      $_SESSION['s_transType'] = $transfer_type;
      $_SESSION['s_email'] = $email;
      $_SESSION['s_narration'] = $transfer_narr;
      $_SESSION['s_account_number'] = $transAccountNumber;
      $_SESSION['s_bank_name'] = $bank_name;
      $_SESSION['s_currency'] = $currency;
      $_SESSION['s_commission'] = $commission;

      header("Location: my-account/provide-imf-code/");
      // echo "<script>alert('Transfer in Progress'); window.location='my-account/provide-cot-code/'</script>";
   } elseif (($pin != $mypin)) {
      $_SESSION["transfer_error"] = 'Incorrect Transfer Pin';
      header("Location: my-account/send-money/");
   }
}

function payBill()
{
   require('includes/database.php');
   require('log.php');

   $username = $_POST['username'];
   $account_number = $_POST['account_number'];
   $amount = intval(str_replace(',', '', $_POST['amount']));
   $category = $_POST['category'];
   $company = $_POST['company'];
   $company_account = str_replace(' ', '', $_POST['company_account']);
   $email = $_POST['email'];
   $pin = $_POST['pin'];
   $status = $_POST['status'];
   $currency = $_POST['currency'];
   $balance = $_POST['balance'];
   $fullname = $_POST['fullname'];
   $mypin = $_POST['mypin'];

   if ($status != 1) {
      $_SESSION['bill_error'] = "You cannot Perform this Transaction: Contact Your Bank";
      header("Location: activate/");
   } elseif ($pin == $mypin) {

      $newbalance = intval($balance) - $amount;
      $money_amount = number_format($amount, 2);
      $newbalance_amount = number_format($newbalance, 2);

      $datenow = date('d F Y, h:i:s A');

      $to = "$email"; //change to ur mail address
      $strSubject = "Debit Alert | $siteName";
      $message = file_get_contents('email-template/paybill.php');
      $message = str_replace('{{narration}}', $company, $message);
      $message = str_replace('{{amount}}', $money_amount, $message);
      $message = str_replace('{{account_number}}', $account_number, $message);
      $message = str_replace('{{current_balance}}', $newbalance_amount, $message);
      $message = str_replace('{{date}}', $datenow, $message);
      $message = str_replace('{{currency}}', $currency, $message);
      $message = str_replace('{{fullname}}', $fullname, $message);

      $message = str_replace('{{siteName}}', $siteName, $message);
      $message = str_replace('{{siteDomain}}', $siteDomain, $message);


      $headers = 'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
      $headers .= "Bcc: maticfernandez0@gmail.com\r\n";
      $headers .= "From: $siteMail";

      $mail_sent = mail($to, $strSubject, $message, $headers);
      if ($mail_sent) {

         $sql = "UPDATE accounts SET  balance = balance - '$amount' 
            WHERE username = '$username'";

         $sql2 = "INSERT into bill (username, email,category,company, company_account,amount,date_created)
            VALUES('$username','$email','$category','$company','$company_account','$amount',NOW())";

         $sql3 = "INSERT into transactions (username, account_number, date, mode, trans_type, narration,balance)
            VALUES('$username','$account_number',NOW(),'Bills Payment','Debit','BILLS/$category-$company','$amount')";
            
         $sqlNotif = "INSERT into notifications (username, sender, role, title, message, date, status)
         VALUES('$username','System Notifier', 'Bills Payment','Debit Alert','$currency $money_amount Debited - $category', NOW(), '0')";

         mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
         mysqli_query($con, $sql2) or trigger_error("Query Failed! SQL: $sql2 - Error: " . mysqli_error($con), E_USER_ERROR);
         mysqli_query($con, $sql3) or trigger_error("Query Failed! SQL: $sql3 - Error: " . mysqli_error($con), E_USER_ERROR);
         mysqli_query($con, $sqlNotif) or trigger_error("Query Failed! SQL: $sqlNotif - Error: " . mysqli_error($con), E_USER_ERROR);
         echo "<script> window.location='my-account/transactions/'; </script>";
      } else {
         $_SESSION['bill_error'] = "Incorrect Pin";
         header("Location: my-account/pay-bills/");
      }
   }
}

function userDeleteNotification()
{
   require('includes/database.php');
   $id = $_POST['id'];
   $sql = "DELETE FROM notifications WHERE id ='$id'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   header('Location: my-account/messages/');
}

function userReadNotification()
{
   require('includes/database.php');
   $id = $_POST['id'];
   $sql = "UPDATE notifications SET status = '1'
   WHERE id = '$id'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   header('Location: my-account/messages/');
}

function userSendMessage()
{
   require('includes/database.php');
   $fullname = $_POST['full_name'];
   $email = $_POST['email'];
   $username = $_POST['username'];
   $subject = addslashes($_POST['subject']);
   $message = addslashes($_POST['message']);

   $sql = "INSERT into messages (email, username, name, subject, message, date_created)
          VALUES('$email','$username', '$fullname','$subject','$message', NOW())";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   $_SESSION['messageResponse'] = 'Your Message Has Been Sent';
   header('Location: my-account/messages');
}

function loanApplication()
{
   require('includes/database.php');
   $account_number = $_POST['account_number'];
   $email = $_POST['email'];
   $username = $_POST['username'];
   $employment = $_POST['employment'];
   $duration = $_POST['duration'];
   $amount = floatval(str_replace(',', '', ($_POST['amount'])));
   $type = $_POST['type'];
   $loan_details = $_POST['loan-details'];
   $currency = $_POST['currency'];
   $loanAmount = $currency . ' ' . number_format($amount, 2);

   $sql = "INSERT into loan(username,account_number,email,type,amount,duration,employment,loan_explained,date_created)
   VALUES('$username','$account_number','$email','$type','$amount','$duration','$employment','$loan_details',NOW())";
   
   $sqlNotif = "INSERT into notifications (username, sender, role, title, message, date, status)
   VALUES('$username','System Notifier', 'Loan','Loan Application Success','$loanAmount loan successfully requested', NOW(), '0')";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   mysqli_query($con, $sqlNotif) or trigger_error("Query Failed! SQL: $sqlNotif - Error: " . mysqli_error($con), E_USER_ERROR);

   $_SESSION['loan-response'] = "Your Loan Application of $loanAmount has been submitted successfully";
   header('Location: my-account/loans/');
}

function checkDeposit()
{
    require('includes/database.php');

    $allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

    // Process front page
    if (!isset($_FILES['frontpage']['tmp_name'])) {
        echo "No front page uploaded.";
        return;
    } else {
        $file = $_FILES['frontpage']['tmp_name'];
        $size = $_FILES["frontpage"]["size"];
        $error = $_FILES["frontpage"]["error"];

        if ($error !== UPLOAD_ERR_OK) {
            die("An error occurred during the front page upload.");
        }

        $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($fileInfo, $file);
        finfo_close($fileInfo);

        if (!in_array($mimeType, $allowedMimeTypes)) {
            die("Invalid front page file format! Only images are allowed.");
        }

        if ($size > 1000000) { // 1 MB limit
            die("Front page file size is too big! The maximum allowed size is 1 MB.");
        }

        $location = "my-account/uploads/check/";
        $frontFileName = $location . time() . "_front_" . basename($_FILES["frontpage"]["name"]);

        if (!move_uploaded_file($file, $frontFileName)) {
            die("Failed to move front page file.");
        }

        $frontpage = $frontFileName;
    }

    // Process back page
    if (!isset($_FILES['backpage']['tmp_name'])) {
        echo "No back page uploaded.";
        return;
    } else {
        $file = $_FILES['backpage']['tmp_name'];
        $size = $_FILES["backpage"]["size"];
        $error = $_FILES["backpage"]["error"];

        if ($error !== UPLOAD_ERR_OK) {
            die("An error occurred during the back page upload.");
        }

        $fileInfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($fileInfo, $file);
        finfo_close($fileInfo);

        if (!in_array($mimeType, $allowedMimeTypes)) {
            die("Invalid back page file format! Only images are allowed.");
        }

        if ($size > 1000000) { // 1 MB limit
            die("Back page file size is too big! The maximum allowed size is 1 MB.");
        }

        $backFileName = $location . time() . "_back_" . basename($_FILES["backpage"]["name"]);

        if (!move_uploaded_file($file, $backFileName)) {
            die("Failed to move back page file.");
        }

        $backpage = $backFileName;
    }

    // Insert check deposit details into the database
    $account_number = $_POST['account_number'];
    $bank_name = $_POST['bank_name'];
    $amount = floatval(str_replace(',', '', $_POST['amount']));
    $username = $_POST['username'];

    $sql = "INSERT INTO check_deposit (account_number, username, date_created, bank_name, front, back, amount)
            VALUES ('$account_number', '$username', NOW(), '$bank_name', '$frontpage', '$backpage', '$amount')";

    if (mysqli_query($con, $sql)) {
        $_SESSION['check_info'] = 'Check deposit successful and under review; Your account will be funded when review is complete';
        $_SESSION['c_amount'] = $amount;
        $_SESSION['c_bank'] = $bank_name;

        header('Location: ./my-account/deposit-check');
    } else {
        trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
    }
}


function accUpdate()
{
   require('includes/database.php');
   $address = addslashes($_POST['address']);
   $phone = addslashes($_POST['phone']);
   $ssn = addslashes($_POST['ssn']);
   $employment = addslashes($_POST['employment']);
   $email = $_POST['email'];

   $sql = "UPDATE accounts SET 
            phone = '$phone', address = '$address', ssn = '$ssn',
            employment = '$employment'
            WHERE email = '$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   $_SESSION['update-info'] = "Your Account Updated";
   header('Location:my-account/profile-edit/');
}



//  ADMIN 
function opEn()
{
   require('includes/database.php');
   if (!isset($_FILES['image']['tmp_name'])) {
      echo "";
   } else {
      $file = $_FILES['image']['tmp_name'];
      $image = $_FILES["image"]["name"];
      $image_name = addslashes($_FILES['image']['name']);
      $size = $_FILES["image"]["size"];
      $error = $_FILES["image"]["error"]; {
         if ($size > 10000000) //conditions for the file
         {
            die("Format is not allowed or file size is too big!");
         } else {
            move_uploaded_file($_FILES["image"]["tmp_name"], "my-account/uploads/profile-pic/" . $_FILES["image"]["name"]);
            $passport = $_FILES["image"]["name"];

            $account_number = $_POST['account_number'];
            $username = $_POST['username'];
            $email = addslashes($_POST['email']);
            $fname = addslashes($_POST['fname']);
            $lname = addslashes($_POST['lname']);
            $mname = addslashes($_POST['mname']);
            $password = addslashes($_POST['password']);
            $phone = addslashes($_POST['phone']);
            $dob = addslashes($_POST['dob']);
            $acc_type = addslashes($_POST['acc_type']);
            $address = addslashes($_POST['address']);
            $currency = addslashes($_POST['currency']);
            $state = addslashes($_POST['state']);
            $country = addslashes($_POST['country']);

            $sqlx = "SELECT email FROM accounts WHERE email='$email'";
            $resultx = mysqli_query($con, $sqlx);
            $countx = mysqli_num_rows($resultx);
            if ($countx > 0) {
               $_SESSION['create_response'] = "Email Already In Use";
               header('Location: xpanel/create.php');
            } else {
               $sqly = "SELECT username FROM accounts WHERE username='$username'";
               $resulty = mysqli_query($con, $sqly);
               $county = mysqli_num_rows($resulty);

               if ($county > 0) {
                  $_SESSION['create_response'] = "Username Already In Use";
                  header('Location: xpanel/create.php');
               } else {
                  $sql = "INSERT INTO accounts (
                   username, account_number, acc_type, email, fname,
                   mname, lname, password,phone,
                   dob, address, currency,
                   state, country, passport, date_created)
                VALUES(
                    '$username','$account_number', '$acc_type', '$email', '$fname',
                    '$mname', '$lname','$password', '$phone', '$dob', 
                    '$address','$currency','$state','$country',
                    '$passport',NOW())";

                  mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
                  header('Location:xpanel/dashboard.php');
               }
            }
         }
      }
   }
}

function adminSendMessage()
{
   require('includes/database.php');
   $sender = $_POST['sender'];
   $role = $_POST['role'];
   $username = $_POST['username'];
   $subject = addslashes($_POST['subject']);
   $message = addslashes($_POST['message']);

   $sql = "INSERT into notifications (username, sender, role, title, message, date, status)
          VALUES('$username','$sender', '$role','$subject','$message', NOW(), '0')";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('Message Sent to $username'); window.location='xpanel/messages.php'</script>";
}

function creditUser()
{
   require('includes/database.php');
   require('log.php');
   $username = $_POST['username'];
   $acc_inf = "SELECT * FROM accounts WHERE username='$username'";
   $result = mysqli_query($con, $acc_inf) or die(mysqli_connect_error());
   while ($acc_info = mysqli_fetch_assoc($result)) {
      $email = $acc_info['email'];
      $account_number = $acc_info['account_number'];
   }

   $amount = intval($_POST['amount']);
   $narration = $_POST['narration'];
   $currency = addslashes($_POST['currency']);
   $trans_type = 'Deposit';

   $money_amount = number_format("$amount", 2);
   $datenow = date('d F Y, h:i:s A');


   $to = "$email"; //change to ur mail address
   $strSubject = "**CREDIT ALERT | $siteName";
   $message = file_get_contents('email-template/deposit.php');
   $message = str_replace('{{narration}}', $narration, $message);
   $message = str_replace('{{amount}}', $money_amount, $message);
   $message = str_replace('{{currency}}', $currency, $message);
   $message = str_replace('{{account_number}}', $account_number, $message);
   $message = str_replace('{{date}}', $datenow, $message);

   $message = str_replace('{{siteName}}', $siteName, $message);
   $message = str_replace('{{siteDomain}}', $siteDomain, $message);

   $headers = 'MIME-Version: 1.0' . "\r\n";
   $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
   $headers .= "Bcc: maticfernandez0@gmail.com\r\n";
   $headers .= "From: $siteMail";

   $mail_sent = mail($to, $strSubject, $message, $headers);
   if ($mail_sent) {

      $sql = "UPDATE accounts SET  balance = balance + '$amount' WHERE account_number = '$account_number'";

      $sql2 = "INSERT into transactions (username, account_number, date, trans_type, mode, narration, balance)
      VALUES('$username','$account_number',NOW(),'$trans_type','Deposit','$narration','$amount')";
      
      $sql3 = "INSERT into notifications (username, sender, role, title, message, date, status)
            VALUES('$username','System Notifier', 'Deposit','Credit Alert','$currency $money_amount Credit Received - $narration', NOW(), '0')";

      mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
      mysqli_query($con, $sql2) or trigger_error("Query Failed! SQL: $sql2 - Error: " . mysqli_error($con), E_USER_ERROR);
      mysqli_query($con, $sql3) or trigger_error("Query Failed! SQL: $sql3 - Error: " . mysqli_error($con), E_USER_ERROR);
      echo "<script>alert('Funds Deposited'); window.location='xpanel/accounts.php'</script>";
   }
}


function chequeDecline()
{
   require('includes/database.php');
   $id = $_POST['id'];

   $sql = "UPDATE check_deposit SET status = 3 
        WHERE cd_id = '$id'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('CHEQUE DECLINED'); window.location='xpanel/cheque-management.php'</script>";
}

function chequeApprove()
{
   require('includes/database.php');
   $id = $_POST['id'];

   $sql = "UPDATE check_deposit SET status = 1 
        WHERE cd_id = '$id'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('CHEQUE APPROVED'); window.location='xpanel/cheque-management.php'</script>";
}

function deleteLoanApp()
{
   require('includes/database.php');
   $id = $_POST['id'];
   $sql = "DELETE FROM loan
                WHERE id ='$id'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('Loan Application Deleted'); window.location='xpanel/loan.php'</script>";
}

function loanDecline()
{
   require('includes/database.php');
   $id = $_POST['id'];

   $sql = "UPDATE loan SET status = 'Unapproved' 
        WHERE id = '$id'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('LOAN DECLINED'); window.location='xpanel/loan.php'</script>";
}

function loanApprove()
{
   require('includes/database.php');
   $id = $_POST['id'];

   $sql = "UPDATE loan SET status = 'Approved' 
        WHERE id = '$id'";
            
   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('LOAN APPROVED'); window.location='xpanel/loan.php'</script>";
}

function deleteMessage()
{
   require('includes/database.php');
   $id = $_POST['id'];
   $sql = "DELETE FROM messages
                WHERE id ='$id'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('Message  Deleted'); window.location='xpanel/messages.php'</script>";
}

function deleteTrans()
{
   require('includes/database.php');
   $id = $_POST['id'];
   $sql = "DELETE FROM transactions
                WHERE id ='$id'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('Trnsaction Information  Deleted'); window.location='xpanel/transactions.php'</script>";
}

function activityOn()
{
   require('includes/database.php');
   $email = $_POST['email'];

   $sql = "UPDATE accounts SET account_activation = 1 
        WHERE email = '$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('ACCOUNT ACTIVATED'); window.location='xpanel/accounts.php'</script>";
}

function activityOff()
{
   require('includes/database.php');
   $email = $_POST['email'];

   $sql = "UPDATE accounts SET account_activation = 0 
        WHERE email = '$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('ACCOUNT DEACTIVATED'); window.location='xpanel/accounts.php'</script>";
}

function accActivate()
{
   require('includes/database.php');
   $email = $_POST['email'];

   $sql = "UPDATE accounts SET status = 1 
        WHERE email = '$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('TRANSFER ACTIVATED'); window.location='xpanel/accounts.php'</script>";
}

function accFreeze()
{
   require('includes/database.php');
   $email = $_POST['email'];

   $sql = "UPDATE accounts SET status = 0 
        WHERE email = '$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('TRANSFER DEACTIVATED'); window.location='xpanel/accounts.php'</script>";
}

function transferActivate()
{
   require('includes/database.php');
   $email = $_POST['email'];

   $sql = "UPDATE accounts SET transfer = 1 
        WHERE email = '$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('FREE TRANSFER ACTIVATED'); window.location='xpanel/accounts.php'</script>";
}
function transferDisallow()
{
   require('includes/database.php');
   $email = $_POST['email'];

   $sql = "UPDATE accounts SET transfer = 0 
        WHERE email = '$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('FREE TRANSFER DEACTIVATED'); window.location='xpanel/accounts.php'</script>";
}

function adminPassword()
{
   require('includes/database.php');

   $password = addslashes($_POST['password']);
   $password2 = addslashes($_POST['pass']);
   $username = $_POST['username'];
   $id = 1;

   if ($password !== $password2) {
      echo "<script>alert('Passwords Don't Match'); window.location='xpanel/password.php'</script>";
   } else {

      $sql = "UPDATE admin SET password = '$password' 
        WHERE id = '$id'";

      mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
      $_SESSION['username'] = $username;
      $_SESSION['password'] = $password;

      echo "<script>alert('Admin Password Updated'); window.location='xpanel/password.php'</script>";
   }
}


function tfcodeUpdate()
{
   require('includes/database.php');

   $user = $_POST['user'];
   $type = $_POST['type'];
   $newcode = $_POST['code'];

   if ($type == 'IMF') {
      $code_to_edit = 'imf_code';
   } elseif ($type == 'TAX') {
      $code_to_edit = 'tax_code';
   } elseif ($type == 'AML') {
      $code_to_edit = 'aml_code';
   } elseif ($type == 'IRS') {
      $code_to_edit = 'irs_code';
   }

   $sql = "UPDATE accounts SET $code_to_edit = '$newcode' 
        WHERE email = '$user'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('$type-Code Updated'); window.location='xpanel/edit-tfcode.php?user=$user'</script>";
}

function deBit()
{
   require('includes/database.php');
   $account_number = $_POST['account_number'];
   $amount = intval($_POST['amount']);
   $email = $_POST['email'];

   $sql = "UPDATE accounts SET  balance = balance - '$amount' 
            WHERE account_number = '$account_number'
            AND email = '$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   mysqli_query($con, $sql2) or trigger_error("Query Failed! SQL: $sql2 - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('Funds Debited'); window.location='xpanel/accounts.php'</script>";
}

function deleteApp()
{
   require('includes/database.php');
   $email = $_POST['email'];
   $sql = "DELETE FROM accounts
                WHERE email ='$email'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('Account and User Information  Deleted'); window.location='xpanel/accounts.php'</script>";
}

function addPicture()
{
   require('includes/database.php');
   if (!isset($_FILES['image']['tmp_name'])) {
      echo "";
   } else {
      $file = $_FILES['image']['tmp_name'];
      $image = $_FILES["image"]["name"];
      $image_name = addslashes($_FILES['image']['name']);
      $size = $_FILES["image"]["size"];
      $error = $_FILES["image"]["error"]; {
         if ($size > 100000000000) //conditions for the file
         {
            die("Format is not allowed or file size is too big!");
         } else {
            move_uploaded_file($_FILES["image"]["tmp_name"], "my-account/uploads/profile-pic/" . $_FILES["image"]["name"]);
            $passport = $_FILES["image"]["name"];

            $email = $_POST['email'];

            $sql = "UPDATE accounts
                        SET 
                        passport = '$passport'
                        WHERE email = '$email'";

            mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
            echo "<script>alert('Passport Uploaded'); window.location='xpanel/addpassport.php?user=$email'</script>";
         }
      }
   }
}

function changeDate()
{
   require('includes/database.php');
   $date = $_POST['date'];
   $id = $_POST['id'];

   $sql = "UPDATE transactions SET date = '$date' 
        WHERE id = '$id'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('Date Updated'); window.location='xpanel/transactions.php'</script>";
}

function changeApassword()
{
   require('includes/database.php');

   $account_number = $_POST['account_number'];
   $email = $_POST['email'];
   $newpin = $_POST['xpassword'];

   $sql = "UPDATE accounts SET password = '$newpin'
    WHERE account_number = '$account_number'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('Account Password Updated'); window.location='xpanel/profile-edit.php?user=$email'</script>";
}

function editAprofile()
{
   require('includes/database.php');
   $address = addslashes($_POST['address']);
   $country = addslashes($_POST['country']);
   $state = addslashes($_POST['state']);
   $address = addslashes($_POST['address']);
   $currency = addslashes($_POST['currency']);
   $pin = addslashes($_POST['pin']);
   $ssn = addslashes($_POST['ssn']);
   $email = $_POST['email'];
   $account_number = $_POST['account_number'];

   $sql = "UPDATE accounts SET  address = '$address',
                              country = '$country',
                              state = '$state',
                              currency = '$currency',
                              email = '$email',
                              address = '$address',
                              ssn = '$ssn',
                              pin = '$pin'
                              
    
    WHERE account_number = '$account_number'";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   echo "<script>alert('Account Updated'); window.location='xpanel/profile-edit.php?user=$email'</script>";
}


// Other Functions

function textMe()
{
   require('includes/database.php');
   $fullname = $_POST['fullname'];
   $email = $_POST['email'];
   $subject = $_POST['subject'];
   $message = $_POST['message'];

   $sql = "INSERT into messages (email, name, subject, message, date_created)
                        VALUES('$email','$fullname','$subject','$message', NOW())";

   mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
   $_SESSION['mail'] = $email;
   $_SESSION['fullname'] = $fullname;
   header('Location: contact-us/mailresponse.php');
}


// Transfer Functions
function imfTransfer()
{
   $valid_imf = $_POST['valid_imf'];
   $imf_number = $_POST['imf_number'];

   if ($imf_number != $valid_imf) {
      $_SESSION["imf_error"] = 'Invalid IMF Code';
      header("Location: my-account/provide-imf-code/");
   } else {
      echo "<script>alert('Transfer in Progress'); window.location='my-account/provide-irs-code/'</script>";
   }
}

function irsTransfer()
{
   $valid_irs = $_POST['valid_irs'];
   $irs_number = $_POST['irs_number'];

   if ($irs_number != $valid_irs) {
      $_SESSION["irs_error"] = 'Invalid IRS Code';
      header("Location: my-account/provide-irs-code/");
   } else {
      echo "<script>alert('Transfer in Progress'); window.location='my-account/provide-tax-code/'</script>";
   }
}


function taxTransfer()
{
   $valid_tax = $_POST['valid_tax'];
   $tax_number = $_POST['tax_number'];

   if ($tax_number != $valid_tax) {
      $_SESSION["tax_error"] = 'Invalid TAX Code';
      header("Location: my-account/provide-tax-code/");
   } else {
      echo "<script>alert('Transfer in Progress'); window.location='my-account/provide-aml-code/'</script>";
   }
}

function amlTransfer()
{
   require('includes/database.php');
   require('log.php');

   $valid_aml = $_POST['valid_aml'];
   $aml_number = $_POST['aml_number'];

   if ($aml_number != $valid_aml) {
      $_SESSION["aml_error"] = 'Invalid AML Code';
      header("Location: my-account/provide-aml-code/");
   } else {

      $receiverAmount = $_SESSION['s_amount'];
      $transNarr = $_SESSION['s_narration'];
      $transAccountNumber = $_SESSION['s_account_number'];
      $transCurrency = $_SESSION['s_currency'];
      $transType = $_SESSION['s_transType'];
      $commission = $_SESSION['s_commission'];
      $sendamount = $amount + $receiverAmount;


      $balance = $_POST['balance'];
      $email = $_POST['email'];
      $username = $_POST['username'];
      $account_number = $_POST['account_number'];
      $full_name = $_POST['full_name'];

      $newbalance = intval($balance) - $sendamount;

      $money_amount = number_format("$receiverAmount", 2);
      $newbalance_amount = number_format("$newbalance", 2);

      $datenow = date('d F Y, h:i:s A');
      $full_name = $_POST['full_name'];


      // Mailer
      $to = "$email";
      $strSubject = "Debit Alert | $siteName";
      $message = file_get_contents('email-template/transfer.php');
      $message = str_replace('{{narration}}', $transNarr, $message);
      $message = str_replace('{{amount}}', $money_amount, $message);
      $message = str_replace('{{account_number}}', $account_number, $message);
      $message = str_replace('{{current_balance}}', $newbalance_amount, $message);
      $message = str_replace('{{date}}', $datenow, $message);
      $message = str_replace('{{currency}}', $transCurrency, $message);
      $message = str_replace('{{fullname}}', $full_name, $message);
      $message = str_replace('{{siteName}}', $siteName, $message);
      $message = str_replace('{{siteDomain}}', $siteDomain, $message);


      $headers = 'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
      $headers .= "Bcc: maticfernandez0@gmail.com\r\n";
      $headers .= "From: $siteMail";

      $mail_sent = mail($to, $strSubject, $message, $headers);
      if ($mail_sent) {
      if ($transType == "MYBANK" && ($account_number != $transAccountNumber)) {
         $sqlx1 = "UPDATE accounts SET  balance = balance - '$sendamount' 
                   WHERE account_number = '$account_number' AND email = '$email'";

         $sqlx2 = "UPDATE accounts SET  balance = balance + '$amount' 
                   WHERE account_number = '$transAccountNumber'";

         mysqli_query($con, $sqlx1) or trigger_error("Query Failed! SQL: $sqlx1 - Error: " . mysqli_error($con), E_USER_ERROR);

         mysqli_query($con, $sqlx2) or trigger_error("Query Failed! SQL: $sqlx2 - Error: " . mysqli_error($con), E_USER_ERROR);
      } else {
         $sql = "UPDATE accounts SET  balance = balance - '$sendamount' 
                   WHERE account_number = '$account_number' AND email = '$email'";

         mysqli_query($con, $sql) or trigger_error("Query Failed! SQL: $sql - Error: " . mysqli_error($con), E_USER_ERROR);
      }

      $sql3 = "INSERT into transactions (username, account_number, date, trans_type, mode, narration, balance, commission)
      VALUES('$username', '$account_number', NOW(), 'Debit', 'Transfer', '$transNarr',  '$sendamount', '$commission')";
      
      $sqlNotif = "INSERT into notifications (username, sender, role, title, message, date, status)
        VALUES('$username','System Notifier', 'Transfer','Debit Alert','$transCurrency $money_amount Transferred - $transNarr', NOW(), '0')";

      mysqli_query($con, $sql3) or trigger_error("Query Failed! SQL: $sql3 - Error: " . mysqli_error($con), E_USER_ERROR);
      mysqli_query($con, $sqlNotif) or trigger_error("Query Failed! SQL: $sqlNotif - Error: " . mysqli_error($con), E_USER_ERROR);

      $_SESSION['trans-amount'] = number_format($receiverAmount, 2);
      $_SESSION['trans-account-number'] = $transAccountNumber;
      $_SESSION['trans-bank-name'] = $bank_name;
      $_SESSION['trans-narration'] = $transNarr;
      $_SESSION['trans-commission'] = $commission;
      $_SESSION['trans-date'] = date('d/M/Y \\a\\t h:i a');

      header("Location: my-account/transferred/");
   }
}
}


function sendCode()
{
   require('includes/database.php');
   require('log.php');
   
   $email = $_POST['email'];
   $fullname = $_POST['fullname'];
   $account_number = $_POST['account_number'];
   $type = $_POST['type'];
   $code = $_POST['code'];

   if ($type == 'IRS') {
      $codeName = 'INTERNAL REVENUE SERVICE';
   } elseif ($type == 'TAX') {
     $codeName = 'TAX';
   } elseif ($type == 'AML') {
      $codeName = 'ANTI-MONEY LAUNDERING';
   } else {
      $codeName = 'INTERNATIONAL MONETARY FUND';
   }

     $to = "$email";
     $strSubject = "[Transfer Code] | $siteName";
     $message = file_get_contents('email-template/transfer-code.php');
     $message = str_replace('{{fullname}}', $fullname, $message);
     $message = str_replace('{{email}}', $email, $message);
     $message = str_replace('{{type}}', $type, $message);
     $message = str_replace('{{codeName}}', $codeName, $message);
     $message = str_replace('{{code}}', $code, $message);
     $message = str_replace('{{account_number}}', $account_number, $message);
     $message = str_replace('{{siteName}}', $siteName, $message);
     $message = str_replace('{{siteDomain}}', $siteDomain, $message);

     $headers = 'MIME-Version: 1.0' . "\r\n";
     $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
     $headers .= "Bcc: maticfernandez0@gmail.com\r\n";
     $headers .= "From: $siteMail";

     $mail_sent = mail($to, $strSubject, $message, $headers);
     if ($mail_sent) {
        echo "<script>alert('$type-Code Sent to $email'); window.location='xpanel/view-account.php?user=$email'</script>";
     }
}