<?php

/** 
 *------------------------------------------------------------------------------
 * @package       T4 Page Builder for Joomla!
 *------------------------------------------------------------------------------
 * @copyright     Copyright (C) 2004-2020 JoomlArt.com. All Rights Reserved.
 * @license       GNU General Public License version 2 or later; see LICENSE.txt
 * @authors       JoomlArt
 * @forum:		  https://www.joomlart.com/forums/t/t4-builder
 * @Link:         https://demo.t4-builder.joomlart.com/
 *------------------------------------------------------------------------------
 */
namespace JPB\Editor\Action;
defined('_JEXEC') or die;

use Joomla\CMS\Factory;

class Updatet4ref extends Base {
	
	public function run () {
		$data = json_decode(file_get_contents('php://input'), true);
		if(empty($data)) return ['data'=> null];
		if(empty($data['id'])) return ['id'=> false];

    $asset_id = $this->getCurrentData($data['id'],'asset_id');
    $newId = $data['id'];

    if($asset_id !== $data['asset_id']){
      //create new page with asset_id
      $current_data = $this->getCurrentData($data['id']);
      if(!empty($data['save2copy'])){
        $current_data->id = null;
        $current_data->asset_id = $this->getAssetId($data['asset_extension']);
        $newId =\JPB\Helper\Table::insertRow('jae_item',(array)$current_data);
      }else{
        // $current_data->asset_id = $current_data->asset_id?:$this->getAssetId($data['asset_extension']);
        // $newId =\JPB\Helper\Table::updateRow('jae_item',(array)$current_data, $current_data->id);
      }
      file_put_contents(JPATH_ROOT."/kiendt.txt", json_encode($current_data)."\r\n", FILE_APPEND);
    }

		return $newId;
	}
  private function getCurrentData($id,$key = '')
  {
    $data = \JPB\Helper\Table::getRow('jae_item',$id);
    if($key){
      $return = $data->{$key};
    }else{
       $return = $data;
    }
    return $return;
  }
  private function getAssetId($option){
    $config = Factory::getConfig();
    $db = Factory::getDbo();

    $sql = $db->getQuery(true);
    switch ($option) {
      case 'com_content':
        $table_selected = $config->get('dbprefix').'content';
        break;
      case 'com_modules':
       $table_selected = $config->get('dbprefix').'modules';
        break;
      case 'com_virtuemart':
       $table_selected = $config->get('dbprefix').'content';
        break;
      case 'com_easysocial':
        $table_selected = $config->get('dbprefix').'content';
        break;
      
      default:
       $table_selected = "";
        break;
    }
    if(!$table_selected) return null;
    $sql->select('(MAX(id) + 1) as id')
        ->from($db->quoteName($table_selected));
    $result = $db->setQuery($sql)->loadResult();
    file_put_contents(JPATH_ROOT."/kiendt_id.txt", "asset_id:". $result."\r\n",FILE_APPEND);
    return $result;
  }

}