<?php

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

/**
 * Event for module Paypal
 *
 * @author CIEXT skeleton
 */
class Paypal_event implements SplObserver
{

    public function update(SplSubject $subject)
    {
        $event_name = $subject->get_event_name();
        $event_data = $subject->get_event_data();
        
        // Update payment table
        if ($event_name == 'update' && !empty($event_data['result'])) {
            $ci = & get_instance();
            $data = $ci->paypal_tmodel->fetch($event_data['id']);
            $ci->load->model('payment/payment_tmodel');
            $payment = $ci->payment_tmodel->fetch_by_type_and_item($this->get_type_id(), $data['id_paypal']);
            $ci->payment_tmodel->update((int) $payment['id_payment'], ['paid' => $data['paid']]);
        }

        // Add data to payment table
        if ($event_name == 'add' && !empty($event_data['id'])) {
            $ci = & get_instance();
            $ci->load->model('payment/payment_tmodel');
            $ci->payment_tmodel->add([
                'id_acl_user'     => $ci->rt_user->id_user,
                'type_id'         => $this->get_type_id(),
                'id_payment_item' => $event_data['id'],
            ]);
        }
    }

    protected function get_type_id()
    {
        $ci = & get_instance();
        $ci->config->load('payment/payment_config');

        return $ci->config->item('payment_types_id')['paypal'];
    }

}
