<?php
namespace WpBookingProAdmin\app\models;
defined('_WPBOOKINGPRO_EXEC') or die;

use Exception;
use WpBookingPro\Factory;
use WpBookingPro\Filesystem\File as FileAlias;
use WpBookingPro\Language\Text;
use WpBookingPro\Mvc\Model\ModelForm;
use WpBookingPro\Form\Form;
use WpBookingPro\Mvc\Model\ModelList;
use WpBookingPro\Registry\Registry;
use WpBookingPro\Utilities\Utility;
use WpBookingProAdmin\app\helpers\AdminHelper;

class PaymentModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "payment";
    /**
     * @var string
     */
    public $table_name = "payment";
    public function save($data = array())
    {
        $input = Factory::getInput();
        if (!$data) {
            $data = $input->getData()['data'];
        }
        $params = array();
        foreach ($data as $key => $value) {
            if (strpos($key, "params") !== false) {
                $key = substr($key, 7);
                $params[$key] = $value;
            }
        }
        $params=reset($params);//TODO: Fix later
        $register = new Registry();
        $register->loadArray($params);
        $data['params'] = $register->toString();
        $payment = parent::save($data); // TODO: Change the autogenerated stub

        $image=Factory::getInput()->files->get('image','','raw');
        $check_user_demo = AdminHelper::checkUserDemo();
        if(!empty($image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $image['name'];
            if($check_user_demo['is_demo']) {
                $short_path_image = "payment/images/cover/$name";
                $new_file_image_appointment_path = WP_CONTENT_DIR . '/uploads/sites/' . $check_user_demo['blog_id'].DS.$short_path_image;

            } else {
                $short_path_image = "upload/payment/images/cover/$name";
                $new_file_image_appointment_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_image;

            }
            if (!FileAlias::write($new_file_image_appointment_path, FileAlias::read($image['tmp_name']))) {
                throw new Exception(Text::_("can not upload image cover"));
            }
            $payment->image = $short_path_image;
            $data_image = (array)$payment;
            $payment = parent::save($data_image);
        }
        return $payment;
    }
    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;
    }
    public function create_payment_by_payment_name($payment_name)
    {
        $data = array(
            "type" => $payment_name,
            "name" => ucfirst($payment_name),
        );
        $payment = parent::save($data);
        return $payment;
    }

}
