<?php

namespace App\Controllers\Member;

use App\Controllers\MemberController;
use App\Models\ShortlinkModel;
use App\Models\ShortlinkHistoryModel;
use App\Models\PayoutModel;
use App\Models\UserModel;

class Shortlink extends MemberController
{
    public function index()
    {
        if($this->data['setting']['shortlink_status'] == "off"){
            $this->session->setFlashdata('msg', faucet_alert(['Shortlink is currently disabled'], 'danger'));
            return redirect()->to(base_url('/member/dashboard'));
        }
        
        // Validate currency against enabled currencies
        $currency = strtoupper($this->data['setting']['currency']);
        $this->data['title'] = "Shortlink";
        $currency = strtoupper($this->data['setting']['currency']);
        $allCurrencies = currency_list($this->data['setting']['microwallet']);
        $this->data['selectedCurrency'] = $currency;
        $this->data['currencyName'] = $allCurrencies[$currency];
        $this->data['price'] = getprice($this->data['currencyName']);
        
        $LinkModel = new ShortlinkModel();
        $LinkHistory = new ShortlinkHistoryModel();
        $time24 = date('Y-m-d H:i:s', strtotime('-24 hours'));
        $userid = $this->data['user']['id'];
        $shortlink = $LinkModel->orderBy('priority', 'ASC')->findAll();
        $history = $LinkHistory->select('COUNT(*) as total, `link_id`')
                ->groupStart()
                    ->where('ip', $this->request->getIPAddress())
                    ->orWhere('user_id', $userid)
                ->groupEnd()
                ->where('time_stamp >', $time24)->groupBy('link_id')->findAll();
        
        $this->data['shortlink'] = $shortlink;
        $this->data['link_history'] = $history;
        $link_view = [];
        $total_reward = 0;
        $total_view = 0;
        foreach($history as $hkey => $hvalue){
            $link_view[$hvalue['link_id']] = $hvalue['total'];
        }
        foreach($shortlink as $key => $value) {
            $remainingViews = $value['view'] - (!empty($link_view[$value['id']]) ? $link_view[$value['id']] : 0);
            $total_view += $remainingViews;
            $sl_reward = max(($value['reward']/$this->data['price']), '0.00000001'); //setting the minimum to be 1 satoshi
            $link_reward = format_amount($sl_reward, 8);
            $total_reward += ($sl_reward * $remainingViews);
            
        }
        $this->data['total_view'] = $total_view;
        $this->data['total_reward'] = $total_reward;
        $this->data['link_data'] = $link_view;
        return $this->render_member('member/shortlink', $this->data);
    }
    
    public function view($linkid = null)
    {
        if($this->data['setting']['shortlink_status'] == "off"){
            $this->session->setFlashdata('msg', faucet_alert(['Shortlink is currently disabled'], 'danger'));
            return redirect()->to(base_url('/member/dashboard'));
        }
        
        // Validate currency against enabled currencies
        $currency = strtoupper($this->data['setting']['currency']);
        $LinkModel = new ShortlinkModel();
        $LinkHistory = new ShortlinkHistoryModel();
        $time24 = date('Y-m-d H:i:s', strtotime('-24 hours'));
        $userid = $this->data['user']['id'];
        $shortlink = $LinkModel->where('id', $linkid)->first();
        if($shortlink) {
            $history = $LinkHistory->select('COUNT(*) as total')
                ->groupStart()
                    ->where('ip', $this->request->getIPAddress())
                    ->orWhere('user_id', $userid)
                ->groupEnd()
                ->where('time_stamp >', $time24)
                ->where('link_id', $linkid)->first();
            if(($shortlink['view'] - $history['total']) > 0){
                $time = time();
                $hash_salt = rand(100000,999999);
                $hash = md5($time.$userid.$linkid.$hash_salt);
                $api_link = str_replace('{url}', site_url('/member/link/back/'.$hash), $shortlink['api_key']);
                $response = json_decode(file_get_contents($api_link), true);
                if(!empty($response['status']) && $response['status'] == "success"){
                    $session_data = [
                        'link_id' => $linkid,
                        'hash' => $hash,
                        'time' => $time,
                        'url' => $response['shortenedUrl'],
                    ];
                    $this->session->set('shortlink', $session_data);
                    return redirect()->to($response['shortenedUrl']);
                }else{
                    $this->session->setFlashdata('msg', faucet_alert(['failed to retrieve link, please try again later'],'danger'));
                    $this->session->setFlashdata('sl', $response);
                    return redirect()->to(base_url('/member/shortlinks'));
                }
            }else{
                $this->session->setFlashdata('msg', faucet_alert(['you have already visited this shortlink, please try other links'],'danger'));
                return redirect()->to(base_url('/member/shortlinks'));
            }
        }else{
            $this->session->setFlashdata('msg', faucet_alert(['shortlink error, please try again'],'danger'));
            return redirect()->to(base_url('/member/shortlinks'));
        }
    }
    
    function back($hash){
        $LinkModel = new ShortlinkModel();
        $LinkHistory = new ShortlinkHistoryModel();
        $UserModel = new UserModel();
        $time24 = date('Y-m-d H:i:s', strtotime('-24 hours'));
        $userid = $this->data['user']['id'];
        $link_session = $this->session->get('shortlink');
        $linkid = $link_session['link_id'];
        $shortlink = $LinkModel->where('id', $linkid)->first();
        if($shortlink) {
            $history = $LinkHistory->select('COUNT(*) as total')
                ->groupStart()
                    ->where('ip', $this->request->getIPAddress())
                    ->orWhere('user_id', $userid)
                ->groupEnd()
                ->where('time_stamp >', $time24)
                ->where('link_id', $linkid)->first();
            if(($shortlink['view'] - $history['total']) < 1){
                $this->session->setFlashdata('msg', faucet_alert(['You have already reached daily limit for this shortlink, visit other shortlinks'],'danger'));
                return redirect()->to(base_url('/member/shortlinks'));
            }else if($link_session['hash'] != $hash){
                $this->session->setFlashdata('msg', faucet_alert(['Link token doesn\'t match, please try again'],'danger'));
                return redirect()->to(base_url('/member/shortlinks'));
            }else if(time() < $link_session['time'] + $this->data['setting']['sl_timer']){
                $this->session->setFlashdata('msg', faucet_alert(['shortlink error, please turn off any bypass or adblocker and try again.'],'danger'));
                return redirect()->to(base_url('/member/shortlinks'));
            }
            //$this->session->remove('shortlink');
            $history_data = [
                'link_id' => $linkid,
                'user_id' => $userid,
                'url' => $link_session['url'],
                'reward' => $shortlink['reward'],
                'ip' => $this->request->getIPAddress(),
                'time_stamp' => date('Y-m-d H:i:s'),
                'hash' => $hash,
            ];

            // Get currency price for the user's selected currency
            $allCurrencies = currency_list($this->data['setting']['microwallet']);
            $currencyPrice = getprice($allCurrencies[$this->data['setting']['currency']]);
            
            $currency_amount = $shortlink['reward'] / $currencyPrice;
            $amount = floor(($currency_amount) * 100000000) > 0 ? floor(($currency_amount) * 100000000): 1; // Round up to integer for FaucetPay API
            
            $send = $this->data['setting']['microwallet'] == 'faucetpay' ? faucetpay($this->data['user']['email'], $this->ip, $amount, $this->data['setting']['faucetpay_key'], $this->data['setting']['currency']) : zexpay($this->data['setting']['zexpay_key'], $currency_amount, $this->data['user']['email'], $this->data['setting']['currency']);
            if($send && $send['status'] == '200'){
                // Add to shortlink history
                $LinkHistory->insert($history_data);
                
                // Add to payout history
                $payoutModel = new PayoutModel();
                $payoutModel->addPayout(
                    $this->data['user']['id'], 
                    $this->data['user']['email'], 
                    $this->data['setting']['currency'], 
                    'shortlink', 
                    $shortlink['reward'], // USD amount
                    $amount / 100000000 // Convert satoshi to decimal
                );

                if($this->data['setting']['ref_bonus'] > 0 && !empty($this->data['user']['ref'])){
                    $ref_amount = max(floor($amount * ($this->data['setting']['ref_bonus'] / 100)), 1);
                    $ref_currency_amount = format_amount(max($currency_amount * ($this->data['setting']['ref_bonus'] / 100), 0.00000001), 8);
                    $UserModel = new UserModel();
                    $ref = $UserModel->getUserById($this->data['user']['ref']);
                    $ref_user = $ref ? $ref['id'] : 0;
                    $ref_address = $ref ? $ref['email'] : $this->data['user']['ref'];
        
                    $send_ref = $this->data['setting']['microwallet'] == 'faucetpay' ? faucetpay($ref_address, $this->ip, $ref_currency_amount, $this->data['setting']['faucetpay_key'], $this->data['setting']['currency'], true) : zexpay($this->data['setting']['zexpay_key'], $ref_currency_amount, $ref_address, $this->data['setting']['currency']);
                    if($send_ref && $send_ref['status'] == '200'){
                    // Add to payout history
                    $payoutModel->addPayout(
                        $ref_user, 
                        $ref_address, 
                        $this->data['setting']['currency'], 
                        'referral', 
                        $shortlink['reward'] * ($this->data['setting']['ref_bonus'] / 100), // USD amount
                        $ref_amount / 100000000 // Convert satoshi to decimal
                    );
                }
                }

                $this->session->setFlashdata('msg', faucet_alert(['You successfully claimed '.format_amount($amount / 100000000, 8).' '.$this->data['setting']['currency']],'success'));
                return redirect()->to(base_url('/member/shortlinks'));
            }else{
                $this->session->setFlashdata('msg', faucet_alert(['Withdrawal failed: ' . $send['message']], 'danger'));
                return redirect()->to(base_url('/member/shortlinks'));
            }

        }else{
            $this->session->setFlashdata('msg', faucet_alert(['unkown error occured, please try again'],'danger'));
            return redirect()->to(base_url('/member/shortlinks'));
        }
    }
    
}
