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

class Cron extends CI_Controller
{

    public function add_daily_growth_new()
    {

        $this->load->model('Adm');
        $this->load->model('Members');

        $rows = $this->Members->get_all_rows_wallet();

        if ($rows) {
            foreach ($rows as $row) {
                $team = $this->Members->getMyTeam($row['user_id']);
                $teamMember = $team ? count($team) : 0;
                // if($teamMember == 0){
                //     $growth = 2;
                // }else{
                //     $growth = 2+$teamMember;
                // }

                $growth = 0.166;
                $percentage = $growth / 100;

                $userId = $row['user_id'];
                $amount =    $row['wallet_amount'] * $percentage;


                $lastRow = $this->Adm->get_daily_growth_by_userid($userId);

                $balance = MemberHelper::user_wallet($userId);

                $data['user_id'] = $userId;
                $data['amount'] = $amount;
                $data['before_amount'] = $balance ? $balance : 0;
                $data['after_amount'] = $balance ? $balance + $amount : $amount;
                $data['day'] = $lastRow ? $lastRow['day'] + 1 : 1;
                $data['created_at'] = date("Y-m-d H:i:s");
                $res = $this->Adm->daily_growth($data);
                if ($res) {

                    $wallet['user_id'] = $userId;
                    $wallet['wallet_amount'] = $amount;
                    $wallet['updated_at'] = date("Y-m-d");
                    $this->Members->add_wallet_amount($userId, $wallet);
                }
            }
        }
    }


    function coinpaymentWebhook()
    {

        $merchant_id = "b5b4992ca04a48a74ccf4c34323249a3";

        $ipn_secret = "gfhj867545##5$$@";

        $debug_email = "s88rufyt4x@pomail.net";



        $txn_id = $_POST['txn_id'];

        $payment = $this->Members->getCoinPaymentByTxn($txn_id);

        $order_currency = $payment['to_currency']; //BTC

        $order_total = $payment['amount_in_btc']; //BTC

        if (!isset($_POST['ipn_mode']) || $_POST['ipn_mode'] != 'hmac') {

            $this->edie("IPN Mode is not HMAC");
        }



        if (!isset($_SERVER['HTTP_HMAC']) || empty($_SERVER['HTTP_HMAC'])) {

            $this->edie("No HMAC Signature Sent.");
        }



        $request = file_get_contents('php://input');

        // return $request;

        if ($request === false || empty($request)) {

            $this->edie("Error in reading Post Data");
        }



        if (!isset($_POST['merchant']) || $_POST['merchant'] != trim($merchant_id)) {

            $this->edie("No or incorrect merchant id.");
        }



        $hmac =  hash_hmac("sha512", $request, trim($ipn_secret));

        if (!hash_equals($hmac, $_SERVER['HTTP_HMAC'])) {

            $this->edie("HMAC signature does not match.");
        }



        $amount1 = floatval($_POST['amount1']); //IN USD

        $amount2 = floatval($_POST['amount2']); //IN BTC

        $currency1 = $_POST['currency1']; //USD

        $currency2 = $_POST['currency2']; //BTC

        $status = intval($_POST['status']);



        if ($currency2 != $order_currency) {

            $this->edie("Currency Mismatch");
        }



        if ($amount2 < $order_total) {

            $this->edie("Amount is lesser than order total");
        }



        if ($status >= 100 || $status == 2) {

            // Payment is complete

            $this->Members->updateCoinPayment($payment['id'], ['status' => 'success']);

            $this->addFunds($payment['user_id'], $payment['amount_in_usd']);
        } else if ($status < 0) {

            // Payment Error

            $this->Members->updateCoinPayment($payment['id'], ['status' => 'error']);
        } else {

            // Payment Pending

            $this->Members->updateCoinPayment($payment['id'], ['status' => 'pending']);
        }

        die("IPN OK");
    }

    function edie($error_msg)
    {

        global $debug_email;

        $report =  "ERROR : " . $error_msg . "\n\n";

        $report .= "POST DATA\n\n";

        foreach ($_POST as $key => $value) {

            $report .= "|$key| = |$value| \n";
        }

        $cpIPN = ['report' => $report, 'created_at' => Helpers::date()];

        $this->Members->saveCoinPaymentIPN($cpIPN);
    }



    // function test()
    // {

    //     $this->addFunds(2, 20.5);
    // }

    function addFunds($userId, $amount)
    {

        $wallet = array();

        $wallet['user_id'] = $userId;

        $wallet['wallet_amount'] = $amount;

        $wallet['updated_at'] = Helpers::date();

        $result = $this->Members->add_wallet_amount($userId, $wallet);

        // if ($result) {

        //     $userObj = Helpers::getUserObj($userId);

        //     // $message = "Hi! " . $userObj['full_name'] . ". We have added $" . $amount . " to your wallet";

        //     // Helpers::SendEmail("Funds Added", $userObj["email"], $message);
        // }
    }
    
    
    public function register_user_mailchimp()
{
    $email= "pefih78458@dxirl.com";
   
    $fname = ''; 
    $lname = '';
    $apiKey = '84dc9947f0d243f8f78b7cbf87e7d0f2-us20';
    $listId = 'ff8432db02';
    $dataCenter = substr($apiKey, strpos($apiKey, '-') + 1); // e.g., us21

    $memberId = md5(strtolower($email));
    $url = "https://$dataCenter.api.mailchimp.com/3.0/lists/$listId/members/$memberId";

    $json = json_encode([
        'email_address' => $email,
        'status_if_new' => 'subscribed',
        'merge_fields'  => [
            'FNAME' => $fname,
            'LNAME' => $lname
        ]
    ]);

    $ch = curl_init($url);

    curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

    $result = curl_exec($ch);

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    echo "<pre>";
 print_r(json_decode($result,true));
exit;
    if ($httpCode == 200) {
        return true; // success
    } else {
        log_message('error', 'Mailchimp API error: ' . $result);
        return false;
    }
}

public function sendTransactionalEmail()
{
    $mandrillApiKey = 'md-kRgx-x5kJCh5-6N7zRG6wQ';
    $toEmail = 'pefih78458@dxirl.com';
    $toName = 'User Name';

    $message = [
        'subject' => 'Welcome to Our Platform',
        'from_email' => 'your@domain.com',
        'from_name' => 'Your Company',
        'to' => [[
            'email' => $toEmail,
            'name'  => $toName,
            'type'  => 'to'
        ]],
        'html' => '<p>Hello <strong>' . $toName . '</strong>,<br>Welcome to our platform!</p>',
    ];

    $postData = [
        'key' => $mandrillApiKey,
        'message' => $message,
    ];

    $ch = curl_init('https://mandrillapp.com/api/1.0/messages/send.json');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $result = curl_exec($ch);
    curl_close($ch);

   echo "<pre>";
 print_r(json_decode($result,true));
exit;
}

public function send_smtp()
{
  
	Helpers::sendEmailNew("Welcome to Defilenders", 'rofopab807@mytaemin.com', "hi");
}


}
