<?php

/**
 * @package      Easyway Shop
 * @copyright    Copyright (C) 2005 - 2013 TA-EDV
 * @license      proprietary
 * @author       Darius Zylka
 * 
 * Program Description:
 * Easyway Shop is an e-commerce system with many features.
 * 
 * File Description:
 * 
 */
include_once './core/config.class.php';

class admin_create_dummies {

	private $layout_object, $base_object;

	function __construct($base_object, $layout_object) {
		$this->layout_object = $layout_object;
		$this->base_object = $base_object;
	}

	public function run() {
		if (isset($_POST['createDummyStructure']) && is_numeric($_POST['createDummyStructure'])) {
			$this->_createStructureDummies($_POST['createDummyStructure'], $_POST['l1'], $_POST['l2'], $_POST['l3']);
		} else if (isset($_POST['killSubStructure']) && is_numeric($_POST['killSubStructure'])) {
			$this->_killStructureSubs($_POST['killSubStructure']);
		}

		return $this->layout_object->fetch('admin_create_dummies.tpl');
	}

	private function _createStructureDummies($structure_id, $l1, $l2, $l3) {
		$this->_killStructureSubs($structure_id);

		for ($i = 1; $i <= $l1; ++$i) {
			$nid1 = $this->_insertStructure($structure_id, 1);

			for ($j = 1; $j <= $l2; ++$j) {
				$nid2 = $this->_insertStructure($nid1, 2);

				for ($k = 1; $k <= $l3; ++$k) {
					$this->_insertStructure($nid2, 3);
				}
			}
		}
	}

	private function _insertStructure($parent_id, $level) {
		$query = "
			INSERT INTO 
				`structure` (
					`parent_id`, `name`, `theme_id`, `active`, `short_uri`, `old_id`, `get_parent_discounts`
				) 
				VALUES (
					" . $parent_id . ", 
					'tmpname', 
					0, 
					1, 
					'tmpsuri', 
					0, 
					0
				)
		";
		$this->base_object->db->query($query);
		$nid = $this->base_object->db->insert_id;

		$name = 'Kind ' . $nid . ' von Papa ' . $parent_id . ' (Sub-Level ' . $level . ')';
		$suri = 'Kind_' . $nid . '_von_Papa_' . $parent_id;
		
		$query = "
			UPDATE
				`structure`
			SET
				`name` = '" . $name . "',
				`short_uri` = '" . $suri . "'
			WHERE
				`id` = " . $nid . "
		";
		$this->base_object->db->query($query);

		return $nid;
	}

	private function _getStructureSubs($structure_id) {
		$sql = "
			SELECT 
				id
			FROM 
				structure
			WHERE 
				parent_id IN (" . $this->base_object->db->real_escape_string($structure_id) . ")
		";
		$p = $this->base_object->db->query($sql);

		$killId = array();
		while ($PO = $p->fetch_object()) {
			$killId[] = $PO->id;
		}
		
		return $killId;
	}
	
	private function _killStructureSubs($structure_id) {
		$killId = $this->_getStructureSubs($structure_id);

		if (count($killId) > 0) {
			$ksql = "
				DELETE FROM
					structure
				WHERE
					id IN (" . implode(', ', $killId) . ")
			";
			$this->base_object->db->query($ksql);

			$ksql = "
				DELETE FROM
					site_content
				WHERE
					structure_id IN (" . implode(', ', $killId) . ")
			";
			$this->base_object->db->query($ksql);
			
			$this->_killStructureSubs(implode(',', $killId));
		}
	}

}
