<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Payment_api extends MY_Controller
{

    public function __construct()
    {
        parent::__construct();

    }

    public function notifications_pp()
    {
        $private_key = 'vt7ZFfj51LSx';
        if (md5($_REQUEST['security_data'] . $private_key) == $_REQUEST['security_hash']) {
            if (strtolower($_REQUEST['payment_status']) == 'completed') {
                $invoice = $_REQUEST['invoice'];
                $order_details = $this->db->where('invoice_id', $invoice)->get('orders')->row();
                if (!$order_details) {
                    $this->output->set_output(json_encode(array('message' => 'Erreur : facture introuvable.')));
                } else if ($order_details->paid == 1) {
                    $this->output->set_output(json_encode(array('message' => 'Erreur : compte déjà crédité.')));
                } else {
                    $this->update_credit($order_details->user_id, $order_details->package, $order_details->id);

                    $this->output->set_output(json_encode(array('message' => 'Succès : compte crédité.')));
                }
            }
        }
    }

    public function notifications()
    {

        $data = json_decode(file_get_contents('php://input'), true);
        $this->output->set_content_type('application/json');

        if ($data['token'] == '0N9RN27S1P1BGPDADWV49YPSBX1V9B' && $data['status'] == 'paid') {
            // ATOMPAY
            $order_details = $this->db->where('invoice_id', $data['invoice'])->get('orders')->row();
            if (!$order_details) {
                $this->output->set_output(json_encode(array('message' => 'Erreur : facture introuvable.')));
            } else if ($order_details->paid == 1) {
                $this->output->set_output(json_encode(array('message' => 'Erreur : compte déjà crédité.')));
            } else {
                $this->update_credit($order_details->user_id, $order_details->package, $order_details->id);

                $this->output->set_output(json_encode(array('message' => 'Succès : compte crédité.')));
            }
        } else if ($data['event_type'] == 'payment_succeeded') {
            // SINGU
            $order_id = $data['content']['object']['metadata']['order_id'];

            $order_details = $this->db->where('invoice_id', $order_id)->get('orders')->row();
            if (!$order_details) {
                $this->output->set_output(json_encode(array('message' => 'Erreur : facture introuvable.')));
            } else if ($order_details->paid == 1) {
                $this->output->set_output(json_encode(array('message' => 'Erreur : compte déjà crédité.')));
            } else {
                if ($order_details->package == 'register') {
                    $email = $data['content']['object']['metadata']['email'];

                    $this->send_invite($email, $order_details->id);
                } else {
                    $this->update_credit($order_details->user_id, $order_details->package, $order_details->id);
                }
                $this->output->set_output(json_encode(array('message' => 'Succès : compte crédité.')));
            }
        } else {
            $this->output->set_output(json_encode(array('message' => 'Erreur : Token invalide ou status impayé.')));
        }
    }

    private function send_invite($email, $order_id)
    {
        $invite_code = random_string('alnum', 45);
        $this->db->insert('invites', array('invite_code' => $invite_code));

        $this->load->library('email', $this->smtp_config());
        $this->email->from('noreply@yggtorrent.qa', 'Yggtorrent');
        $this->email->subject('Invitation pour créer un compte - Yggtorrent');
        $url = 'https://www.yggtorrent.top/invite/register?invite_code=' . $invite_code;
        $msg = 'Pour créer un compte sur YggTorrent veuillez cliquer sur le lien ci-dessous :';
        $msg .= '<br><br><a href="' . $url . '">' . $url . '</a><br><br>';
        $this->email->message($msg);
        $this->email->to($email);
        $this->email->send();

        $this->db->where('id', $order_id)->update('orders', ['paid' => 1]);

    }

    private function smtp_config()
    {
        $config = array(
            'protocol' => 'smtp',
            'smtp_host' => 'smtp.elasticemail.com',
            'smtp_port' => 2525,
            'smtp_user' => 'noreply@yggtorrent.wtf',
            'smtp_pass' => '7C5F5F6A7C379065D771329D397741F3C76B',
            'mailtype' => 'html',
        );
        $config['crlf'] = "\r\n";
        $config['newline'] = "\r\n";
        return $config;
    }


    private function update_credit($user_id, $package, $order_id)
    {
        if (filter_var($user_id, FILTER_VALIDATE_INT)) {
            $user_data = $this->db->where('id', $user_id)->get('users')->row();
            if (isset($user_data->id)) {
                $valid_order = false;
                $freeleech = false;
                // Offre 10
                if ($package == 'basic') {
                    $valid_order = true;
                    $bonus_go = 60;
                }
                // Offre 20
                if ($package == 'standard') {
                    $valid_order = true;
                    $bonus_go = 210;
                }
                // Offre 40
                if ($package == 'premium') {
                    $valid_order = true;
                    $freeleech = true;
                    if ($user_data->end_freeleech > 0) {
                        $freeleech = strtotime('+10 days', $user_data->end_freeleech);
                    } else {
                        $freeleech = strtotime('+10 days', now());
                    }
                    $bonus_go = 720;
                }
                // Offre 79.99
                if ($package == 'vip') {
                    $valid_order = true;
                    $freeleech = true;
                    if ($user_data->end_freeleech > 0) {
                        $freeleech = strtotime('+45 days', $user_data->end_freeleech);
                    } else {
                        $freeleech = strtotime('+45 days', now());
                    }
                    $bonus_go = 4000;
                }
                if ($valid_order) {
                    $update = [
                        'uploaded' => $user_data->uploaded + (1073741824 * $bonus_go),
                        'can_leech' => 1,
                        'is_donator' => 1,
                    ];
                    if ($freeleech) {
                        $update['end_freeleech'] = $freeleech;
                        $update['download_multiplier'] = 0;
                    }
                    $this->db->where('id', $user_data->id)->update('users', $update);
                    $this->db->where('id', $order_id)->update('orders', ['paid' => 1]);
                }
            }
        }
    }

    public function ratzo()
    {
        $this->output->set_content_type('application/json');
        $data = json_decode(file_get_contents('php://input'), true);

        if ($data['token'] == '0N9RNXXXS1P1BGPDAXXXXPSBX1V9') {
            $orders = $this->db->select('id, amount, processor')
                ->where('paid', 1)
                ->order_by('id', 'desc')
                ->limit(50)
                ->get('orders')
                ->result_array();

            foreach ($orders as &$order) {
                $order['id'] = (int) $order['id'];
                $order['amount'] = (float) $order['amount'];
            }

            $this->output->set_output(json_encode($orders));

        }


    }


}
