<?php
if (!defined('BASEPATH')) {
    die('Direct access to the script is not allowed');
}

$client = $conn->prepare("SELECT * FROM clients WHERE client_id=:id");
$client->execute(["id" => $_SESSION['msmbilisim_userid']]);
$client = $client->fetchAll(PDO::FETCH_ASSOC);
$client = $client[0];

if ($_POST && $_POST["username"]) :
    foreach ($_POST as $key => $value) :
        $_SESSION["data"][$key] = $value;
    endforeach;

    $receiver_username = htmlspecialchars($_POST["username"]);
    $amount = htmlentities($_POST["amount"]);

    // Fetching transfer fees
    $fees = $conn->prepare("SELECT fundstransfer_fees FROM settings");
    $fees->execute([]);
    $fees = $fees->fetchAll(PDO::FETCH_ASSOC);
    $fees = $fees[0]['fundstransfer_fees'];

    // Validation for amount
    if (!is_numeric($amount) OR !($amount > 0)) {
        $error = 1;
        $errorText = $languageArray["transferfunds.bank.amountNotNumeric"];
    } elseif ($client['balance'] < $amount) {
        $error = 1;
        $errorText = $languageArray["transferfunds.bank.enoughBalance"];
    } else {
        $receiver = $conn->prepare("SELECT * FROM clients WHERE username=:username && client_id !=:id");
        $receiver->execute(["username" => $receiver_username, "id" => $_SESSION['msmbilisim_userid']]);
        $receiver = $receiver->fetchAll(PDO::FETCH_ASSOC);
        $receiver = $receiver[0];
        $receiver_id = $receiver['client_id'];

        if (count($receiver) == 0) {
            $error = 1;
            $errorText = $languageArray["transferfunds.bank.usernameNotFound"];
        } else {
      // Calculate fee and after-fee amount
$feeAmount = $amount * $fees / 100;  // Tax/fee amount
$afterFees = $amount - $feeAmount;  // Amount received by receiver

// Deduct only the sent amount (not including the fee) from the sender's balance
$exec = $conn->prepare("UPDATE clients SET balance = balance - :amount WHERE client_id=:id");
$exec->execute(["amount" => $amount, "id" => $client['client_id']]);

// Update the receiver's balance with the after-fee amount
$exec = $conn->prepare("UPDATE clients SET balance = balance + :afterFees WHERE client_id=:id");
$exec->execute(["afterFees" => $afterFees, "id" => $receiver_id]);

// 1. Log payment for the sender (deducting the sent amount, not including fee)
$insert = $conn->prepare("INSERT INTO payments SET 
    payment_status=:status, 
    payment_mode=:mode, 
    payment_amount=:amount, 
    payment_bank=:bank, 
    payment_method=:method, 
    payment_delivery=:delivery, 
    payment_note=:note, 
    payment_extra=:note,
    payment_update_date=:date, 
    payment_create_date=:date2, 
    client_id=:client_id, 
    client_balance=:balance");

$insert->execute(array(
    "status" => 3, 
    "delivery" => 2, 
    "bank" => 0, 
    "mode" => "Manuel",
    "amount" => -$amount,  // Subtract the amount sent (not including the fee)
    "method" => 55, 
    "note" => "Transfer funds to " . $receiver_username,
    "date" => date("Y-m-d H:i:s"), 
    "date2" => date("Y-m-d H:i:s"),
    "balance" => $client['balance'], 
    "client_id" => $client["client_id"]
));

// 2. Log payment for the receiver (amount received after fee deduction)
$insert2 = $conn->prepare("INSERT INTO payments SET 
    payment_status=:status, 
    payment_mode=:mode, 
    payment_amount=:amount, 
    payment_bank=:bank, 
    payment_method=:method, 
    payment_delivery=:delivery, 
    payment_note=:note, 
     payment_extra=:note,
    payment_update_date=:date, 
    payment_create_date=:date2, 
    client_id=:client_id, 
    client_balance=:balance");

$insert2->execute(array(
    "status" => 3, 
    "delivery" => 2, 
    "bank" => 0, 
    "mode" => "Manuel",
    "amount" => $afterFees,  // Receiver gets the amount after the fee
    "method" => 55, 
    "note" => "Transferred funds from " . $client['username'],
    "date" => date("Y-m-d H:i:s"), 
    "date2" => date("Y-m-d H:i:s"),
    "balance" => $receiver['balance'], 
    "client_id" => $receiver["client_id"]
));



           
// Compose HTML message for the receiver
$receiver_msg = "
    <html>
        <head>
            <style>
                .body {
                    font-family: Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                }
                .email-container {
                    max-width: 600px;
                    margin: 0 auto;
                    padding: 20px;
                    background-color: #f4f4f4;
                    border-radius: 8px;
                }
                .email-header {
                    text-align: center;
                    font-size: 22px;
                    font-weight: bold;
                    color: #333;
                }
                .email-content {
                    margin-top: 20px;
                    font-size: 16px;
                    color: #555;
                }
                .important {
                    font-weight: bold;
                    color: #333;
                }
                .cta-link {
                    text-decoration: none;
                    font-weight: bold;
                    display: block;
                    text-align: center;
                    margin-top: 10px;
                    padding: 15px 25px;
                    font-size: 18px;
                    background-color: #007bff; /* Blue for CTA link */
                    color: white;
                    border-radius: 5px;
                    transition: background-color 0.3s ease;
                }
                .cta-link:hover {
                    background-color: #0056b3;
                }
                .footer {
                    font-size: 14px;
                    color: #777;
                    text-align: center;
                    margin-top: 30px;
                }
                /* Full-Width Money Button */
                .money-button2 {
                    
                    background-color: #28a745; /* Green for receiver */
                    color: white;
                     text-decoration: none;
                    font-weight: bold;
                    display: block;
                    text-align: center;
                    margin-top: 10px;
                    padding: 15px 25px;
                    font-size: 18px;
                    
                    color: white;
                    border-radius: 5px;
                    transition: background-color 0.3s ease;
                }
                .money-button2:hover {
                    background-color: #218838;
                }
                .amount {
                    font-weight: bold;
                    font-size: 20px;
                    color: #fff;
                }
            </style>
        </head>
        <div class='body'>
            <div class='email-container'>
                <div class='email-header'>
                    Hello, $receiver_username,
                </div>
                <div class='email-content'>
                    <p><span class='important'>" . $client['username'] . "</span> has successfully transferred <span class='important'>₹" . $amount . "</span> to your wallet after service Tax.</p>
                    <a href='#' class='money-button2'>
                       <span class='amount'>₹" . $afterFees . "</span>
                    </a>
                    <p>The funds have been successfully received. You can log in to your account to view the updated balance:</p>
                    <a href='" . site_url() . "' class='cta-link'>Login to Your Account</a>
                    <p>If you have any issues or need assistance, please contact our support team by opening a ticket. You can do so by visiting the link below:</p>
                    <a href='" . site_url() . "tickets/' class='cta-link'>Contact Admin</a>
                    <p class='footer'>Thank you for using our services!</p>
                </div>
            </div>
        </div>
    </html>
";

// Compose HTML message for the sender
$sender_msg = "
    <html>
        <head>
            <style>
                .body {
                    font-family: Arial, sans-serif;
                    line-height: 1.6;
                    color: #333;
                }
                .email-container {
                    max-width: 600px;
                    margin: 0 auto;
                    padding: 20px;
                    background-color: #f4f4f4;
                    border-radius: 8px;
                }
                .email-header {
                    text-align: center;
                    font-size: 22px;
                    font-weight: bold;
                    color: #333;
                }
                .email-content {
                    margin-top: 20px;
                    font-size: 16px;
                    color: #555;
                }
                .important {
                    font-weight: bold;
                    color: #333;
                }
                .cta-link {
                    text-decoration: none;
                    font-weight: bold;
                    display: block;
                    text-align: center;
                    margin-top: 10px;
                    padding: 15px 25px;
                    font-size: 18px;
                    background-color: #007bff; /* Blue for CTA link */
                    color: white;
                    border-radius: 5px;
                    transition: background-color 0.3s ease;
                }
                .cta-link:hover {
                    background-color: #0056b3;
                }
                .footer {
                    font-size: 14px;
                    color: #777;
                    text-align: center;
                    margin-top: 30px;
                }
                /* Full-Width Money Button */
                .money-button {
                     text-decoration: none;
                    font-weight: bold;
                    display: block;
                    text-align: center;
                    margin-top: 10px;
                    padding: 15px 25px;
                    font-size: 18px;
                    background-color: #007bff; /* Blue for CTA link */
                    color: white;
                    border-radius: 5px;
                    transition: background-color 0.3s ease;
                    background-color: #dc3545; /* Red for sender */
                    color: white;
                    
                }
                .money-button:hover {
                    background-color: #c82333;
                }
                .amount {
                    font-weight: bold;
                    font-size: 20px;
                    color: #fff;
                }
            </style>
        </head>
        <div class='body'>
            <div class='email-container'>
                <div class='email-header'>
                    Hello, " . $client['username'] . ",
                </div>
                <div class='email-content'>
                    <p>You have successfully transferred <span class='important'>₹" .$amount  . "</span> to <span class='important'>$receiver_username</span> after service Tax.</p>
                    <a href='#' class='money-button'>
                       <span class='amount'>₹" . $afterFees . "</span>
                    </a>
                    <p>The funds have been successfully received by the recipient. You can log in to your account to view the updated balance:</p>
                    <a href='" . site_url() . "' class='cta-link'>Login to Your Account</a>
                    <p>If you have any issues or need assistance, please contact our support team by opening a ticket. You can do so by visiting the link below:</p>
                    <a href='" . site_url() . "tickets/' class='cta-link'>Contact Admin</a>
                    <p class='footer'>Thank you for using our services!</p>
                </div>
            </div>
        </div>
    </html>
";



            // Set email headers for HTML content
            $from =  $settings["smtp_user"]; 
            $fromName = $settings["site_seo"]; 
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-Type: text/html; charset=UTF-8" . "\r\n";
            // Use the dynamic email from the $settings array
           $headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n"; 
        //   Dynamically set the From email

            // Send email to receiver
            $send_receiver = mail($receiver["email"], "Funds Received Successfully", $receiver_msg, $headers);

            // Send email to sender
            $send_sender = mail($client["email"], "Funds Transferred Successfully", $sender_msg, $headers);

            $success = 1;
            $successText = str_replace("{name}", $receiver_username, $languageArray["transferfunds.bank.done"]);
        }
    }

endif;

if( $payment_url ):
    echo '<script>setTimeout(function(){window.location="' . $payment_url . '"},1000)</script>';
endif;
?>
