<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Donation extends MY_Controller
{
    public function __construct()
    {
        parent::__construct();

        $no_logged_methods = array();

        if (empty($this->session->logged) && !in_array($this->router->fetch_method(), $no_logged_methods)) {
            $this->session->set_flashdata('show_login_form', true);
            redirect('engine/error?http_code=403');
        }
    }

    public function wp_processor_limit()
    {
        echo $this->cache->redis->get('ppwp');
    }

    public function card_processor_limit()
    {
        echo $this->cache->redis->get('stripe');
    }

    public function create_order()
    {
        $package = $this->input->get('package', true);
        $processor = $this->input->get('processor', true);

        // Vérification de la validité du package et du processeur
        $packages = $this->config->item('packages');
        $processors = $this->config->item('processors');

        if (!isset($packages[$package]) || !isset($processors[$processor])) {
            return $this->return_error('Invalid package or processor.');
        }

        $amount = $packages[$package]['amount'];
        $product_id = $packages[$package]['product_id'];
        $email = $this->session->userdata('email');
        $username = $this->session->userdata('nickname');

        // Gestion spécifique pour PayPal
        if ($processor === 'pp' && $amount < $this->cache->redis->get('ppwp')) {
            $invoice_url = "https://www2.ygg.boutique/wp-json/custom/v1/add_to_cart_and_checkout/?product_id={$product_id}&quantity=1&email={$email}&username={$username}";

            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(array(
                    'status' => 'success',
                    'invoice_page' => $invoice_url
                )));
            // Gestion spécifique pour Stripe Aging-Process
        } else if ($processor === 'cc1') {
            /*  if ($amount < $this->cache->redis->get('stripe')) {
                $invoice_url = "https://www4.ygg.boutique/wp-json/custom/v1/pay/?product_id={$product_id}&quantity=1&email={$email}&username={$username}";

                return $this->output->set_content_type('application/json')
                    ->set_output(json_encode(array(
                        'status' => 'success',
                        'invoice_page' => $invoice_url
                    )));
                // Gestion spécifique pour Stripe Viet
            } else {*/
            /*$invoice_url = "https://www3.ygg.boutique/wp-json/custom/v1/add_to_cart_and_checkout/?product_id={$product_id}&quantity=1&email={$email}&username={$username}";

            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(array(
                    'status' => 'success',
                    'invoice_page' => $invoice_url
                )));
            //  }*/

            $invoice_url = "https://www5.ygg.boutique/wp-json/custom/v1/add_to_cart_and_checkout/?product_id={$product_id}&quantity=1&email={$email}&username={$username}";

            return $this->output->set_content_type('application/json')
                ->set_output(json_encode(array(
                    'status' => 'success',
                    'invoice_page' => $invoice_url
                )));
        }


        // Traitement du paiement
        $response = $this->process_payment($processor, $amount, $package);

        if (!$response['invoice_id']) {
            return $this->return_error($response['message']);
        }

        $this->record_transaction($response, $package, $processor, $amount);

        return $this->output->set_content_type('application/json')
            ->set_output(json_encode(array(
                'invoice_id' => $response['invoice_id'],
                'package' => $package,
                'amount' => $amount,
                'processor' => $processor,
                'invoice_page' => $response['invoice_page']
            )));
    }

    private function process_payment($processor, $amount, $package)
    {
        $response = false;
        $packages = $this->config->item('packages');
        $package_title = $packages[$package]['title'];

        switch ($processor) {
            case 'cc1':
                $response = $this->_generate_cc1_invoice($amount, $package_title);
                break;
            case 'pp':
                $max_amount = $this->cache->redis->get('pp');
                if (round($amount * 1.20 * 1.07, 2) < $max_amount) {
                    $response = $this->_generate_paypal_invoice($amount, $package_title);
                } else {
                    $response = $this->_generate_paypal_fsh_invoice($amount, $package_title);
                }
                break;
            case 'crypto':
                $response = $this->_generate_atompay_invoice($amount);
                break;
            default:
                return ['success' => false, 'message' => "Payment processor '$processor' not supported."];
        }

        return $response ?: ['message' => "Failed to create invoice using $processor."];
    }


    private function record_transaction($response, $package, $processor, $amount)
    {
        $user_id = $this->session->id;
        $this->db->insert('orders_tracking', [
            'user_id' => $user_id,
            'payment' => $processor,
            'nickname' => $this->session->nickname,
            'downloaded' => $this->session->downloaded,
            'uploaded' => $this->session->uploaded,
            'ratio' => round($this->session->uploaded / $this->session->downloaded, 3),
            'can_leech' => $this->session->can_leech,
            'created_at' => time()
        ]);

        $this->db->insert('orders', [
            'user_id' => $user_id,
            'invoice_id' => $response['invoice_id'],
            'invoice_page' => $response['invoice_page'],
            'processor' => $processor,
            'package' => $package,
            'amount' => $amount,
            'created' => time()
        ]);
    }

    // FSH Signature
    private function __generate_signature_fsh($params = [])
    {
        ksort($params);
        return hash_hmac("sha256", base64_encode(json_encode($params)), $this->config->item('fsh_secret'));
    }

    // PayPal FSH Invoice
    private function _generate_paypal_fsh_invoice($amount, $product)
    {
        $amount = round($amount * 1.23, 2);
        $invoice_id = generate_invoice_number();

        $data = array(
            'request_id' => $invoice_id,
            'email' => $this->session->email,
            'name' => $this->session->nickname,
            'amount' => $amount,
            'description' => $product,
            'cancel_url' => 'https://www.ygg.re/donation/bonus/payment_refused',
            'return_url' => 'https://www.ygg.re/donation/bonus/payment_accepted',
            'notify_url' => 'https://2p7uocpccaevslbls0gubo.hooks.webhookrelay.com',
            'method' => 'PAYPAL',
            'currency' => 'EUR'
        );

        $jsonData = json_encode($data);
        $api = 'https://fshpay.com/api/create-order';
        $ch = curl_init($api);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Authorization: client_id=' . $this->config->item('fsh_public') . '&signature=' . $this->__generate_signature_fsh($data),
            'Content-Type: application/json'
        ));

        $output = curl_exec($ch);
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($output === false || $httpStatusCode != 200) {
            return false;
        }

        $output = json_decode($output, true);

        if (json_last_error() !== JSON_ERROR_NONE || !isset($output['payment_url'])) {
            return false;
        }

        return [
            'invoice_id' => $invoice_id,
            'invoice_page' =>  $output['payment_url']
        ];
    }

    // PayPal Invoice
    private function _generate_paypal_invoice($amount, $product)
    {
        $amount = round($amount * 1.20 * 1.07, 2);
        $invoice_id = generate_invoice_id();
        $url = 'https://yfl.boats/';
        $params = [
            'public_key' => 'tzqbuxpx4VvI',
            'item_name' => $product,
            'item_number' => 1,
            'price' => $amount,
            'return' => 'https://www.ygg.re/donation/bonus/payment_accepted',
            'cancel_return' => 'https://www.ygg.re/donation/bonus/payment_refused',
            'notify_url' => 'https://www3.yggtorrent.cool/ipn/payments',
            'invoice' => $invoice_id
        ];
        $query = http_build_query($params);
        $fullUrl = $url . '?' . $query;

        return ['invoice_id' => $invoice_id, 'invoice_page' => $fullUrl];
    }

    // AtomPay Invoice
    private function _generate_atompay_invoice($amount)
    {
        $data = array(
            'amount' => $amount,
            'currency' => 'eur',
            'token' => $this->config->item('atompay_secret')
        );

        $jsonData = json_encode($data);
        $api = 'https://atompay.co/api/create-invoice/crypto';
        $ch = curl_init($api);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

        $output = curl_exec($ch);
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($output === false || $httpStatusCode != 200) {
            return false;
        }

        $output = json_decode($output, true);

        if (json_last_error() !== JSON_ERROR_NONE || !isset($output['invoice_id'])) {
            return false;
        }

        return ['invoice_id' => $output['invoice_id'], 'invoice_page' =>  'https://atompay.co/invoice/' . $output['invoice_id']];
    }

    // CC1 turkish Invoice
    private function _generate_cc1_invoice($amount, $product)
    {
        $invoice_id = generate_invoice_id();
        $postData = array(
            'user' => '714285',
            'pin' => 'XH4NJMI9RIWHMLSYPP5Y',
            'email' => $this->session->email,
            'orderId' => $invoice_id,
            'Price' => $amount,
            'CurrencyCode' => 'EUR',
            'SuccessURL' => 'https://www.ygg.re/donation/bonus/payment_accepted',
            'ErrorURL' => 'https://www.ygg.re/donation/bonus/payment_refused',
            'ipnUrl' => 'https://miwrt3szxozwhyqdyyzqae.hooks.webhookrelay.com',
            'PaymentContent' => $product . ' - Unlimited',
            'subscriptions' => 1,
        );
        $api = 'https://3d.snappypayment.com/Wd3pay/getSecurePaymentUrl';
        $ch = curl_init($api);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($output === false || $httpStatusCode != 200) {
            return false;
        }

        try {
            $response = new SimpleXMLElement($output);
        } catch (Exception $e) {
            return false;
        }
        return ['invoice_id' => $invoice_id, 'invoice_page' => (string) $response->url];
    }

    public function buy_crypto()
    {
        $this->load->view('donation/buy_crypto');
    }

    public function bonus($action = '')
    {
        $data = array();
        $data['aborted_download'] = false;
        if ($action == 'payment_accepted') {
            $data['credit_card_message'] = true;
        } else if ($action == 'pending_confirmation') {
            $data['crypto_message'] = true;
        } else if ($action == 'disabled') {
            $data['disabled_message'] = true;
        } else if ($action == 'payment_refused') {
            $data['payment_refused'] = true;
        }
        if (isset($_GET['abort_download'])) {
            $torrent_id = $this->input->get('abort_download', true);
            $torrent = $this->db->where('id', $torrent_id)->get('torrents')->row();

            if (isset($torrent->id)) {
                $futuredownload = $torrent->size + $this->session->downloaded;
                $missingupload = $futuredownload - $this->session->uploaded;

                if ($missingupload > 0) {
                    $data['aborted_download'] = true;
                    $data['aborted_torrent_name'] = $torrent->name;
                    $data['aborted_torrent_size'] = bytesToSize($torrent->size);
                    $data['missing_go'] = bytesToSize($missingupload);
                }
            }
        }

        $this->load->view('donation/bonus_trusted_users', $data);
    }

    public function history()
    {
        $this->load->view('donation/history');
    }

    private function return_error($message)
    {
        return $this->output->set_content_type('application/json')
            ->set_output(json_encode(array(
                'status' => 'error',
                'message' => $message
            )));
    }
}
