<?php
namespace WpBookingHotelAdmin\app\models;
defined('_WPBOOKINGHOTEL_EXEC') or die;

use Exception;
use WpBookingHotel\Factory;
use WpBookingHotel\Filesystem\File as FileAlias;
use WpBookingHotel\Language\Text;
use WpBookingHotel\Mvc\Model\ModelForm;
use WpBookingHotel\Form\Form;
use WpBookingHotel\Mvc\Model\ModelList;
use WpBookingHotel\Registry\Registry;
use WpBookingHotel\Utilities\Utility;

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');
        if(!empty($image['name'])) {
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $image['name'];
            $short_path_image = "upload/payment/images/cover/$name";
            $new_file_image_hotel_path = WPBOOKINGHOTEL_PATH_ROOT . DS . $short_path_image;
            if (!FileAlias::write($new_file_image_hotel_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;
    }

}
