<?php

use app\libraries\paypal\PaypalClient;

if (!defined('BASEPATH')) exit('No direct script access allowed');

class Invoice_payment_paypal_model extends MY_Model
{
    public $database;
    public $short = "r";
    public $table;
    public $tbl;

    const STATUS_PENDING = 'pending';
    const STATUS_PAID = 'paid';
    const STATUS_CANCELLED = 'cancelled';

    public function __construct()
    {
        parent::__construct();
        $this->database = $this->getTenantNo();
        $this->tbl = 'invoicing_invoice_payment_paypal';
        $this->table = $this->tbl . ' ' . $this->short;
    }


    public function add_invoice_payment_paypal($params)
    {
        $id = $this->insertDB($this->database, $this->tbl, $params, false, [
            'updated_at' => date("Y-m-d H:i:s"),
            'created_at' => date("Y-m-d H:i:s")
        ]);

        return $id;
    }

    public function update_invoice_payment_paypal($params, $invoice_ids, $payment_id)
    {
        $this->db = $this->load->database($this->database, true);
        $this->saveWhereDB(
            $this->database,
            $this->tbl,
            $params,
            ['invoice_ids' => json_encode($invoice_ids), 'payment_id' => $payment_id],
            ['updated_at' => date('Y-m-d H:i:s')]
        );
    }

    public function paypal_create_payment($payment_description, $params, $member, $success_url, $cancel_url)
    {
        $item_list = [];
        $client = new PaypalClient();
        $client->payment_description = $payment_description;

        if (!empty($params['payment_total'])) $client->payment_total = doubleval($params['payment_total']);
        if (!empty($params['payment_currency'])) $client->payment_currency = $params['payment_currency'];
        if (!empty($params['product_json'])) $item_list = $params['product_json'];

        $client->success_url = $success_url;
        $client->cancel_url = $cancel_url;



        $client->migrate_to_paypal_item_list($item_list, [
            // 'recipient_name' => $member['display_name'],
            // 'line_1' => $params['shipping_address_1'],
            // 'line_2' => $params['shipping_address_2'] . ' ' . $params['shipping_address_3'],
            // 'phone' => $member['phone'],
            // 'country_code' => 'HK'
        ]);
        return $client->create_payment();
    }

    public function paypal_execute($payment_id, $payer_id)
    {
        $client = new PaypalClient();

        return $client->execute($payment_id, $payer_id);
    }

    public function paypal_exception($invoice_ids, $payment_id, $e)
    {
        return $this->update_invoice_payment_paypal([
            'state'     => 'failed',
            'exception' => (string) $e,
        ], $invoice_ids, $payment_id);
    }
}
