<?php
defined('_WPBOOKINGPRO_EXEC') or die;
use WooBooking\CMS\Filesystem\File;
use Woobooking\CMS\Registry\Registry;
use WooBooking\CMS\Utilities\Utility;
if(!class_exists("WpBookingPro_PaymentModel")) {
    /**
     * Class WpBookingPro_PaymentModel
     */
    class WpBookingPro_PaymentModel extends WoobookingModelForm
    {
        /**
         * @var string
         */
        public $table_name = "payment";
        /**
         * @var string
         */
        public $context = "payment";

        /**
         * @param array $data
         * @return array|bool|object
         * @throws Exception
         */
        public function save($data = array())
        {
            $input = Factory::getInput();
            $data = $input->getData()['data'];
            $params = $data['params'];
            $data['params'] = json_encode($params);
            $image = $data['image'];
            unset($data['image']);
            $payment = parent::save($data); // TODO: Change the autogenerated stub
            if ($image) {
                if ($image) {
                    $name = str_replace(' ', '_',Utility::random_string_by_time()) . $image['name'];
                    $new_file_cover_path = WPBOOKINGPRO_PATH_ROOT . "/upload/payment/images/$name";
                    $data_image = $image['data'];
                    $data_image = base64_decode($data_image); // decode an image
                    if (!File::write($new_file_cover_path, $data_image)) {
                        throw new Exception("can not upload image cover");
                    }
                    $payment->image = Utility::get_short_file_by_path($new_file_cover_path);
                }
                $payment = parent::save((array)$payment);
            }
            return $payment;
        }

        /**
         * @param $payment_name
         * @return array|bool|object
         */
        public function create_payment_by_payment_name($payment_name)
        {
            $data = array(
                "type" => $payment_name,
                "name" => ucfirst($payment_name),
            );
            $payment = parent::save($data);
            return $payment;
        }

        /**
         * @param int $id
         * @return mixed
         */
        public function getItem($id = 0)
        {
            $item = parent::getItem($id); // TODO: Change the autogenerated stub
            $register = new Registry();
            $register->loadString($item->params);
            $item->params = $register;
            return $item;
        }
    }
}