<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Withdraw extends Admin_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('form_validation');
    }
    public function today()
    {
        $skip = (isset($_GET['per_page']) && is_numeric($_GET['per_page'])) ? $_GET['per_page'] : 0;

        $this->data['page'] = 'Withdraw today';

        $this->load->library('pagination');
        $this->load->config('pagination');
        $config = $this->config->item('pagination_config');

        $this->data['history'] = $this->m_admin->getTotalWithdrawals($skip);
        $config['base_url'] = site_url('admin/withdraw/today/');
        $config['total_rows'] = $this->m_admin->countTotalWithdrawals();

        $config['page_query_string'] = TRUE;
        $this->pagination->initialize($config);
        $this->data['pagination'] = $this->pagination->create_links();
        $this->render('withdraw_history', $this->data);
    }

    public function yesterday()
    {
        $skip = (isset($_GET['per_page']) && is_numeric($_GET['per_page'])) ? $_GET['per_page'] : 0;

        $this->data['page'] = 'Yesterday withdrawals';

        $this->load->library('pagination');
        $this->load->config('pagination');
        $config = $this->config->item('pagination_config');

        $this->data['history'] = $this->m_admin->getTotalWithdrawalsYesterday($skip);
        $config['base_url'] = site_url('admin/withdraw/yesterday/');
        $config['total_rows'] = $this->m_admin->countTotalWithdrawalsYesterday();

        $config['page_query_string'] = TRUE;
        $this->pagination->initialize($config);
        $this->data['pagination'] = $this->pagination->create_links();
        $this->render('withdraw_history', $this->data);
    }

    public function recent()
    {
        $this->data['page'] = 'Recent withdrawals';
        $this->data['history'] = $this->m_admin->getRecentWithdrawals();
        $this->data['pagination'] = '';
        $this->render('withdraw_history', $this->data);
    }

    public function pending()
    {
        $this->data['page'] = 'Pending Withdrawals';
        $this->data['pendingWithdrawal'] = $this->m_admin->getPendingWithdrawal();
        $this->render('withdrawals', $this->data);
    }
    
    public function accept_all() {
    $ids = $this->input->post('ids');
    
        foreach ($ids as $id) {
            $this->load->model('m_dashboard');
        $id = $this->db->escape_str($id);
        $data = $this->m_admin->get_withdrawal($id);
        $method = $this->m_core->getCurrency($data['method']);
        $amount = $data['amount'];
        $coinAmount = number_format($amount / $method['price'], 8);
$coinAmount = rtrim($coinAmount, '0'); // Remove trailing zeros

// If $coinAmount becomes empty, set it to '0'
$coinAmount = !empty($coinAmount) ? $coinAmount : '0';
        $satoshiAmount = floor($amount * 100000000 / $method['price']);
        $this->load->helper('string');
		$this->load->model('m_auth');
		$this->data = $this->m_core->getSettings();
		$user_email = $this->m_admin->get_withdrawalEmail($id);
		$siteName = "FireCash";
		$activeUrl = site_url('/withdraw');
		$message = <<<EOT
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Template</title>
    <style>
        /* Add your custom styles here */
        body {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            width: 100%;
            background-color: #fff;
            margin: 0;
        }
        .container {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            vertical-align: top;
            display: block !important;
            max-width: 600px !important;
            clear: both !important;
            margin: 0 auto;
        }
        .content {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            max-width: 600px;
            display: block;
            margin: 0 auto;
            padding: 20px;
        }
        .main {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            border-radius: 3px;
            margin: 0;
            border: none;
            width: 100%;
        }
        .content-wrap {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            color: #495057;
            font-size: 14px;
            vertical-align: top;
            margin: 0;
            padding: 30px;
            box-shadow: 0 0.75rem 1.5rem rgba(18, 38, 63, .03);
            border-radius: 7px;
            background-color: #fff;
        }
        .content-block {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            vertical-align: top;
            margin: 0;
            padding: 0 0 20px;
        }
        a {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            color: #FFF;
            text-decoration: none;
            line-height: 2em;
            font-weight: bold;
            text-align: center;
            cursor: pointer;
            display: inline-block;
            border-radius: 5px;
            text-transform: capitalize;
            background-color: #34c38f;
            margin: 0;
            border-color: #34c38f;
            border-style: solid;
            border-width: 8px 16px;
        }
    </style>
</head>
<body>
    <table class="body-wrap">
        <tr>
            <td></td>
            <td class="container">
                <div class="content">
                    <table class="main">
                        <tr>
                            <td class="content-wrap">
                                <meta itemprop="name" content="Confirm Email">
                                <table width="100%" cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td class="content-block">
                                            Your withdrawal request of $coinAmount {$method['code']} . {$method['wallet']} . was successful.
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="content-block">
                                            You can check withdrawal status and history by clicking on this button:
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="content-block" itemprop="handler" itemscope="" itemtype="http://schema.org/HttpActionHandler">
                                            <a href="$activeUrl" itemprop="url">Fire Cash</a>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="content-block">
                                            <b>$siteName</b>
                                            <p>Support Team</p>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </div>
            </td>
        </tr>
    </table>
</body>
</html>
EOT;


        if ($method['wallet'] == 'faucetpay') {
            $result = faucetpay($data['wallet'], $data['ip_address'], $satoshiAmount, $method['api'], $method['code'], $referral = false);
            if ($result["status"] == 200) {
                sendMail($user_email, 'Withdrawal success', $message, $this->data);
                $this->m_dashboard->processPayment($id);
                $this->session->set_flashdata('message', faucet_alert('success', $coinAmount . ' ' . $method['code'] . ' has been sent to ' . $data['wallet']));
                $this->m_core->addNotification($data['user_id'], "Your pending withdrawal #" . $id . " was processed.", 1);
            } else {
                $this->session->set_flashdata('message', faucet_alert('warning', $result['message']));
            }
        } else if ($method['wallet'] == 'expresscrypto') {
            include APPPATH . 'third_party/expresscrypto.php';
            $expresscrypto = new ExpressCryptoV2($method['api'], $method['token'], $data['ip_address']);
            $result = $expresscrypto->sendPayment($data['wallet'], $method['code'], $satoshiAmount);
            if ($result["status"] == 200) {
                $this->m_dashboard->processPayment($id);
                $this->session->set_flashdata('message', faucet_alert('success', $coinAmount . ' ' . $method['code'] . ' has been sent to ' . $data['wallet']));
                $this->m_core->addNotification($data['user_id'], "Your pending withdrawal #" . $id . " was processed.", 1);
            } else {
                $this->session->set_flashdata('message', faucet_alert('warning', $result['message']));
            }
        } else if ($method['wallet'] == 'payeer') {
            include APPPATH . 'third_party/payeer.php';
            $payeer = new CPayeer($method['account_number'], $method['api_id'], $method['api']);
            if ($payeer->isAuth()) {
                $arTransfer = $payeer->transfer(array(
                    'curIn' => 'USD',
                    'sum' => $amount,
                    'curOut' => $method['code'],
                    //'sumOut' => 1,
                    'to' => $data['wallet'],
                    'comment' => 'Payment from' . $this->data['settings']['name']
                ));
                if (empty($arTransfer['errors'])) {
                    $this->m_dashboard->processPayment($id);
                    $this->session->set_flashdata('message', faucet_alert('success', $coinAmount . ' ' . $method['code'] . ' has been sent to ' . $data['wallet']));
                    $this->m_core->addNotification($data['user_id'], "Your pending withdrawal #" . $id . " was processed.", 1);
                } else {
                    $this->session->set_flashdata('withdraw_message', faucet_alert('warning', 'Error! Please try again (' . $arTransfer["errors"][0] . ')'));
                }
            } else {
                $this->session->set_flashdata('withdraw_message', faucet_alert('warning', 'Error! Please try again (' . $payeer->getErrors()[0] . ')'));
            }
        } else if ($method['wallet'] == 'custom') {
            $this->m_dashboard->processPayment($id);
            $this->m_core->addNotification($data['user_id'], "Your pending withdrawal #" . $id . " was processed.", 1);
            $this->session->set_flashdata('message', faucet_alert('success', 'Done'));
            sendMail($user_email, 'Withdrawal success', $message, $this->data);
        }
        }
        $this->session->set_flashdata('message', 'All withdrawals have been processed successfully.');
    return redirect(site_url('/admin/withdraw/pending'));
}

    public function accept($id)
    {
        $this->load->model('m_dashboard');
        $id = $this->db->escape_str($id);
        $data = $this->m_admin->get_withdrawal($id);
        $method = $this->m_core->getCurrency($data['method']);
        $amount = $data['amount'];
        $coinAmount = number_format($amount / $method['price'], 8);
$coinAmount = rtrim($coinAmount, '0'); // Remove trailing zeros

// If $coinAmount becomes empty, set it to '0'
$coinAmount = !empty($coinAmount) ? $coinAmount : '0';
        $satoshiAmount = floor($amount * 100000000 / $method['price']);
        $this->load->helper('string');
		$this->load->model('m_auth');
		$this->data = $this->m_core->getSettings();
		$user_email = $this->m_admin->get_withdrawalEmail($id);
		$siteName = "FireCash";
		$activeUrl = site_url('/withdraw');
		$message = <<<EOT
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Email Template</title>
    <style>
        /* Add your custom styles here */
        body {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            width: 100%;
            background-color: #fff;
            margin: 0;
        }
        .container {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            vertical-align: top;
            display: block !important;
            max-width: 600px !important;
            clear: both !important;
            margin: 0 auto;
        }
        .content {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            max-width: 600px;
            display: block;
            margin: 0 auto;
            padding: 20px;
        }
        .main {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            border-radius: 3px;
            margin: 0;
            border: none;
            width: 100%;
        }
        .content-wrap {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            color: #495057;
            font-size: 14px;
            vertical-align: top;
            margin: 0;
            padding: 30px;
            box-shadow: 0 0.75rem 1.5rem rgba(18, 38, 63, .03);
            border-radius: 7px;
            background-color: #fff;
        }
        .content-block {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            vertical-align: top;
            margin: 0;
            padding: 0 0 20px;
        }
        a {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            box-sizing: border-box;
            font-size: 14px;
            color: #FFF;
            text-decoration: none;
            line-height: 2em;
            font-weight: bold;
            text-align: center;
            cursor: pointer;
            display: inline-block;
            border-radius: 5px;
            text-transform: capitalize;
            background-color: #34c38f;
            margin: 0;
            border-color: #34c38f;
            border-style: solid;
            border-width: 8px 16px;
        }
    </style>
</head>
<body>
    <table class="body-wrap">
        <tr>
            <td></td>
            <td class="container">
                <div class="content">
                    <table class="main">
                        <tr>
                            <td class="content-wrap">
                                <meta itemprop="name" content="Confirm Email">
                                <table width="100%" cellpadding="0" cellspacing="0">
                                    <tr>
                                        <td class="content-block">
                                            Your withdrawal request of $coinAmount {$method['code']} . {$method['wallet']} . was successful.
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="content-block">
                                            You can check withdrawal status and history by clicking on this button:
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="content-block" itemprop="handler" itemscope="" itemtype="http://schema.org/HttpActionHandler">
                                            <a href="$activeUrl" itemprop="url">Fire Cash</a>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td class="content-block">
                                            <b>$siteName</b>
                                            <p>Support Team</p>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </div>
            </td>
        </tr>
    </table>
</body>
</html>
EOT;


        if ($method['wallet'] == 'faucetpay') {
            $result = faucetpay($data['wallet'], $data['ip_address'], $satoshiAmount, $method['api'], $method['code'], $referral = false);
            if ($result["status"] == 200) {
                sendMail($user_email, 'Withdrawal success', $message, $this->data);
                $this->m_dashboard->processPayment($id);
                $this->session->set_flashdata('message', faucet_alert('success', $coinAmount . ' ' . $method['code'] . ' has been sent to ' . $data['wallet']));
                $this->m_core->addNotification($data['user_id'], "Your pending withdrawal #" . $id . " was processed.", 1);
            } else {
                $this->session->set_flashdata('message', faucet_alert('warning', $result['message']));
            }
        } else if ($method['wallet'] == 'expresscrypto') {
            include APPPATH . 'third_party/expresscrypto.php';
            $expresscrypto = new ExpressCryptoV2($method['api'], $method['token'], $data['ip_address']);
            $result = $expresscrypto->sendPayment($data['wallet'], $method['code'], $satoshiAmount);
            if ($result["status"] == 200) {
                $this->m_dashboard->processPayment($id);
                $this->session->set_flashdata('message', faucet_alert('success', $coinAmount . ' ' . $method['code'] . ' has been sent to ' . $data['wallet']));
                $this->m_core->addNotification($data['user_id'], "Your pending withdrawal #" . $id . " was processed.", 1);
            } else {
                $this->session->set_flashdata('message', faucet_alert('warning', $result['message']));
            }
        } else if ($method['wallet'] == 'payeer') {
            include APPPATH . 'third_party/payeer.php';
            $payeer = new CPayeer($method['account_number'], $method['api_id'], $method['api']);
            if ($payeer->isAuth()) {
                $arTransfer = $payeer->transfer(array(
                    'curIn' => 'USD',
                    'sum' => $amount,
                    'curOut' => $method['code'],
                    //'sumOut' => 1,
                    'to' => $data['wallet'],
                    'comment' => 'Payment from' . $this->data['settings']['name']
                ));
                if (empty($arTransfer['errors'])) {
                    $this->m_dashboard->processPayment($id);
                    $this->session->set_flashdata('message', faucet_alert('success', $coinAmount . ' ' . $method['code'] . ' has been sent to ' . $data['wallet']));
                    $this->m_core->addNotification($data['user_id'], "Your pending withdrawal #" . $id . " was processed.", 1);
                } else {
                    $this->session->set_flashdata('withdraw_message', faucet_alert('warning', 'Error! Please try again (' . $arTransfer["errors"][0] . ')'));
                }
            } else {
                $this->session->set_flashdata('withdraw_message', faucet_alert('warning', 'Error! Please try again (' . $payeer->getErrors()[0] . ')'));
            }
        } else if ($method['wallet'] == 'custom') {
            $this->m_dashboard->processPayment($id);
            $this->m_core->addNotification($data['user_id'], "Your pending withdrawal #" . $id . " was processed.", 1);
            $this->session->set_flashdata('message', faucet_alert('success', 'Done'));
            sendMail($user_email, 'Withdrawal success', $message, $this->data);
        }
        return redirect(site_url('/admin/withdraw/pending'));
    }

    public function deny($id)
    {
        $this->load->model('m_dashboard');
        $data = $this->m_admin->get_withdrawal($id);
        $this->m_admin->rewardUser($data['user_id'], $data['amount'], 0, 0);
        $this->m_admin->denyPayment($id);
        $this->m_core->addNotification($data['user_id'], "Your pending withdrawal #" . $id . " was denied.", 2);
        return redirect(site_url('/admin/withdraw/pending'));
    }
}
