<?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\Model;
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 ServiceModel extends ModelForm
{
    /**
     * @var string
     */
    public $context = "service";
    /**
     * @var string
     */
    public $table_name = "service";
    public function getListEmployee($service_id) {
        $query = $this->_db->getQuery(true);
        $query->select('service_employee.employee_id')
            ->from($this->getTableName('service_employee'). ' service_employee')
            ->where('service_employee.service_id='.(int)$service_id)
            ;
        $list_employee = $this->_db->setQuery($query)->loadColumn();
        return $list_employee;
    }
    public function save($data = array())
    {
        $data['user_id'] = $data['user_id'] ? $data['user_id'] : 0;
        $is_new = (isset($data['id']) && $data['id'] != '' && is_numeric($data['id']))?false:true;
        $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();
        $service =  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 = "service/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/service/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"));
            }
            $service->image = $short_path_image;
            $data_image = (array)$service;
            $service = parent::save($data_image);
        }

        $galleryModel=Model::getInstance('gallery');

        $gallery=Factory::getInput()->files->get('gallery','','raw');
        if($gallery && count($gallery["name"]))for($i=0;$i<count($gallery["name"]);$i++){
            $name = str_replace(' ', '_',Utility::gen_random_string()) . $gallery['name'][$i];
            if($check_user_demo['is_demo']) {
                $short_path_image = "services/gallery/$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/services/gallery/$name";
                $new_file_image_appointment_path = WPBOOKINGPRO_PATH_ROOT . DS . $short_path_image;
            }
            if (!FileAlias::write($new_file_image_appointment_path, FileAlias::read($gallery['tmp_name'][$i]))) {
                throw new Exception(Text::_("can not upload image gallery"));
            }

            $service->gallery[] = $short_path_image;

            $data_gallery=array(
                "id"=>0,
                "type"=>AdminHelper::getWpBookingServiceKey(),
                "object_id"=>$service->id,
                "path"=>$short_path_image,
                "name"=>$gallery['name'][$i],
            );
            $galleryModel->save($data_gallery);
        }
        if(isset($data['list_image_gallery_deleted'])) {
            $list_image_gallery_deleted = $data['list_image_gallery_deleted'];
            $list_image_gallery_deleted = (array)json_decode($list_image_gallery_deleted);
        }else{
            $list_image_gallery_deleted=array();
        }
        if(count($list_image_gallery_deleted))foreach ($list_image_gallery_deleted as $id){
            $galleryModel->delete($id);
        }
        $query = $this->_db->getQuery(true);
        $list_employee_id = isset($data['list_employee_id'])?$data['list_employee_id']:array();
        $query->clear()
            ->delete($this->getTableName('service_employee'))
            ->where('service_id=' . (int)$service->id);
        $this->_db->setQuery($query)->execute();
        foreach ($list_employee_id as $employee_id) {
            $query->clear()
                ->insert($this->getTableName('service_employee'))
                ->set('service_id=' . (int)$service->id)
                ->set('employee_id=' . (int)$employee_id)
                ->set('enable_customize=0')
                ->set('start_time00:00:00=')
                ->set('end_time=00:00:00')
                ->set('price=0')
                ->set('minimum_capacity=0')
                ->set('maximum_capacity=')
                ->set('description=description');
            $this->_db->setQuery($query)->execute();
        }


        if ( class_exists( 'WooCommerce' ) ) {
            if ($is_new && $service->open_source_link_id == "") {
                self::createProductions($service);
                $product = self::createProductions($service);
                $productId = $product->get_id();

                if ($productId != null) {
                    //get product just insert (get id product)
                    $service->open_source_link_id = $productId;
                }
                $service = parent::save((array)$service);

            } else {
                $open_source_product_id = $service->open_source_link_id;
                $_product = wc_get_product($open_source_product_id);
                $category_id = $service->category_id;
                $modelCategory = Model::getInstance('category');
                $_category = $modelCategory->getItem($category_id);

                if (!$_product) {
                    $service->open_source_link_id = "";
                    $product = self::createProductions($service);
                    $productId = $product->get_id();

                    if ($productId != null) {
                        //get product just insert (get id product)
                        $service->open_source_link_id = $productId;

                    }
                    $service = parent::save((array)$service);
                } else {
                    $appConfig = Factory::getAppConfig();
                    $is_edit_sync_on_woommerce = $appConfig->get('is_edit_sync_on_woommerce', 0);
                    if ($is_edit_sync_on_woommerce) {
                        $_product->set_name($service->name);
                        $_product->set_slug(strtolower(str_replace(' ', '-', $service->name)));
                        wp_update_post(array('ID' => $open_source_product_id, 'post_content' => $service->description));
                        wp_set_object_terms($open_source_product_id, $_category->name, 'product_cat');
                        update_post_meta($open_source_product_id, '_price', $service->price);
                        $image_url = Factory::getRootUrlPlugin() . '/' . $service->image;
                        self::Generate_Featured_Image($image_url, $open_source_product_id);
                        // get gallery image
                        $db = Factory::getDBO();
                        $query = $db->getQuery(true);
                        $query->select('gallery.path')
                            ->from(Utility::getTableName('gallery') . ' AS gallery')
                            ->where('gallery.object_id=' . (int)$service->id)
                            ->where('gallery.type=' . $query->quote(AdminHelper::getWpBookingServiceKey()));
                        $gallery_image_url = $db->setQuery($query)->loadColumn();
                        foreach ($gallery_image_url as &$image_url) {
                            $image_url = Factory::getRootUrlPlugin() . '/' . $image_url;
                        }

                        self::Generate_Featured_Image_Gallery($gallery_image_url, $open_source_product_id);
                        $_product->save();
                    }

                }

                //insert new the same (A)
            }
        }
        return $service;
    }

    public static function createProductions($service){

        //insert new service to product woocome
        $post = array(
            'post_content' => $service->description,
            'post_status' => "publish",
            'post_title' => $service->name,
            'post_parent' => '',
            'post_type' => "product",
            'post_author'=> 1,

        );

        $wp_filetype = wp_check_filetype($service->image, null);

        //Create post
        $post_id = wp_insert_post( $post );
        $category_id = $service->category_id;
        $modelCategory = Model::getInstance('category');
        $_category = $modelCategory->getItem($category_id);
        wp_set_object_terms( $post_id, $_category->name, 'product_cat' );
        update_post_meta( $post_id, '_price', $service->price );
        $image_url = Factory::getRootUrlPlugin().'/'.$service->image;
        self::Generate_Featured_Image($image_url,$post_id);
        // get gallery image
        $db = Factory::getDBO();
        $query = $db->getQuery(true);
        $query->select('gallery.path')
            ->from(Utility::getTableName('gallery').' AS gallery')
            ->where('gallery.object_id='.(int)$service->id)
            ->where('gallery.type='.$query->quote(AdminHelper::getWpBookingServiceKey()))
            ;
        $gallery_image_url = $db->setQuery($query)->loadColumn();
        foreach ($gallery_image_url as &$image_url) {
            $image_url = Factory::getRootUrlPlugin().'/'.$image_url;
        }

        self::Generate_Featured_Image_Gallery($gallery_image_url, $post_id);

        $_product = wc_get_product( $post_id );

        return $_product;

    }
    public function getItem($id = 0)
    {
        $item = parent::getItem($id); // TODO: Change the autogenerated stub
        if ($item) {
            $db = Factory::getDBO();
            $query = $db->getQuery(true);
            $query->clear()
                ->select('gallery.*')
                ->from($this->getTableName('gallery') . ' AS gallery')
                ->where('object_id=' . (int)$item->id)
                ->where('type=' . $query->quote(AdminHelper::getWpBookingServiceKey()));
            $item->gallery = $db->setQuery($query)->loadObjectList();
            $query->clear()
                ->select('service_employee.employee_id')
                ->from($this->getTableName('service_employee') . ' AS service_employee')
                ->where('service_id=' . (int)$item->id);
            $item->list_employee_id = $db->setQuery($query)->loadColumn();
            $query->clear()
                ->select('location.id')
                ->from($this->getTableName('location') . ' AS location')
                ->where('location.id=' . (int)$item->location_id);
            $item->location_id = $db->setQuery($query)->loadResult();
            $query->clear()
                ->select('country.countryname')
                ->from($this->getTableName('country').' AS country')
                ->where('country.phonecode='.(int)$item->phonecode)
                ->where('country.countrycode='.$query->quote($item->countrycode))
            ;
            $item->country_name = $this->_db->setQuery($query)->loadResult();
            $register = new Registry();
            $register->loadString($item->params);
            $item->params = $register;
        }

        return $item;
    }

    public static function Generate_Featured_Image( $image_url, $post_id  ){
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once (ABSPATH . '/wp-admin/includes/file.php');
            WP_Filesystem();
        }

        $upload_dir = wp_upload_dir();
        if(file_exists($image_url)) {
            $image_data = $wp_filesystem->get_contents($image_url);
            $filename = basename($image_url);
            if(wp_mkdir_p($upload_dir['path'])) {
                $file = $upload_dir['path'] . '/' . $filename;
            } else  {
                $file = $upload_dir['basedir'] . '/' . $filename;
            }
            $wp_filesystem->put_contents($file, $image_data);

            $wp_filetype = wp_check_filetype($filename, null );
            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => sanitize_file_name($filename),
                'post_content' => '',
                'post_status' => 'inherit'
            );
            $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
            require_once(ABSPATH . 'wp-admin/includes/image.php');
            $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
            $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
            $res2= set_post_thumbnail( $post_id, $attach_id );
        }

    }
    public static function Generate_Featured_Image_Gallery( $arr_image_url, $post_id  ){
        global $wp_filesystem;
        if (empty($wp_filesystem)) {
            require_once (ABSPATH . '/wp-admin/includes/file.php');
            WP_Filesystem();
        }
        $upload_dir = wp_upload_dir();
        $image_id_array=[];
        foreach ($arr_image_url as $image_url) {
            if(file_exists($image_url)) {
                $image_data = $wp_filesystem->get_contents($image_url);
                $filename = basename($image_url);
                if(wp_mkdir_p($upload_dir['path'])) {
                    $file = $upload_dir['path'] . '/' . $filename;
                } else  {
                    $file = $upload_dir['basedir'] . '/' . $filename;
                }
                $wp_filesystem->put_contents($file, $image_data);

                $wp_filetype = wp_check_filetype($filename, null );
                $attachment = array(
                    'post_mime_type' => $wp_filetype['type'],
                    'post_title' => sanitize_file_name($filename),
                    'post_content' => '',
                    'post_status' => 'inherit'
                );
                $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
                require_once(ABSPATH . 'wp-admin/includes/image.php');
                $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                $res1= wp_update_attachment_metadata( $attach_id, $attach_data );
                array_push($image_id_array,$attach_id);
            }
        }
        if(count((array)$image_id_array)) {
            update_post_meta($post_id, '_product_image_gallery', implode(',',$image_id_array));
        }
    }
}
