Anda di halaman 1dari 50

<?

php
class CartController extends AppController {

var $name = 'Cart';

var $contents = null;

var $uses = array('Item', 'StockBooking', 'Cart', 'ShippingPriceModel', 'User');

//PUBLIC FUNCTIONS
function beforeFilter() {
parent::beforeFilter();
//$this->Cookie->destroy();
//check if a Cart exists
if(!is_null($this->Session->read('Cart.id'))) {
$this->Cart->id = $this->Session->read('Cart.id');
$cart = $this->Cart->read();
$this->contents = unserialize($cart['Cart']['contents']);
$this->contents['General']['cart_true'] = '1';
}
$this->layout = 'cart';
//$this->_prd($this->Cookie->read());
}

function index() {
if($this->contents['General']['cart_true'] == '1') {
//$this->_prd($this->Cookie->read());
//$i = count($this->contents['Lineitem']);
//$this->_prd($i);
$this->set('cart', $this->contents);
$this->render('cart');
} else {

$this->render('no_cart');
}
}

function check() {

if($this->_testData($this->data) && !empty($this->data)) {

//using the dates input, firstly make them useful, then compare them to the cookie - update
cookie if required.

$start = strtotime($this->data['Date']['start']);
$end = strtotime($this->data['Date']['end']);

$qty = $this->data['StockBooking']['qty'];

//now lets go through the booking working out where the ship date and return dates will fall.
//NB NO COLLECTION AT THE WEEKEND OR BANKHOLIDAY so no need to
calculate shipback date.
$dates = $this->_calculateDates($start, $end);

//now we have our dates array then we need to turn that into something that we can use to
check the stock with.
//lets keep this in the StockBooking model for now, it makes most sense that way!

//first lets get a stocklist for that item.

$conditions = array(
'conditions' => array(
'Stock.item_id' => $this->data['Item']['id'],
'Stock.active' => '1',
));
$this->Item->Stock->contain();
$stockList = $this->Item->Stock->find('all', $conditions);
unset($conditions);

//then we work out which ones have got bookings and which ones don't
if(is_array($checkedStock = $this->Item->Stock->StockBooking->checkDates($stockList,
$dates, $qty))) {

//if checkedStock is an array then we have the right number in stock and available.
//so, lets get a price on those babies and then send this all back to the view.
$item = $this->data['Item']['id'];
$price = $this->_getPrice($item, $qty, $dates);

$this->set('price', $price);
$this->set('number', $checkedStock);

$form['Date.start'] = $this->data['Date']['start'];
$form['Date.end'] = $this->data['Date']['end'];
$form['StockBooking.qty'] = count($checkedStock);
//$this->_prd($checkedStock);
$form['Item.id'] = $this->data['Item']['id'];
$form['Item.name'] = $this->data['Item']['name'];

$this->set('form', $form);
$this->render('success');

} elseif ($checkedStock > 0) {


$item = $this->data['Item']['id'];
$price = $this->_getPrice($item, $checkedStock, $dates);

$this->set('price', $price);
$this->set('number', $checkedStock);

$form['Date.start'] = $this->data['Date']['start'];
$form['Date.end'] = $this->data['Date']['end'];
$form['StockBooking.qty'] = $checkedStock;
$form['Item.id'] = $this->data['Item']['id'];
$form['Item.name'] = $this->data['Item']['name'];
$this->set('form', $form);
$this->render('partial_success');
} else {
$this->render('failure');
}

//$this->_prd($checkedStock);
}
}

function add() {

if($this->_checkUnique()) {

$start = strtotime($this->data['Date']['start']);
$end = strtotime($this->data['Date']['end']);

$qty = $this->data['StockBooking']['qty'];

//now lets go through the booking working out where the ship date and return dates will fall.
//NB NO COLLECTION AT THE WEEKEND OR BANKHOLIDAY so no need to
calculate shipback date.

$dates = $this->_calculateDates($start, $end);

//now we have our dates array then we need to turn that into something that we can use to
check the stock with.
//lets keep this in the StockBooking model for now, it makes most sense that way!

//first lets get a stocklist for that item.

$conditions = array(
'conditions' => array(
'Stock.item_id' => $this->data['Item']['id'],
'Stock.active' => '1',
));
$this->Item->Stock->contain();
$stockList = $this->Item->Stock->find('all', $conditions);
unset($conditions);

//then we work out which ones have got bookings and which ones don't
if(is_array($checkedStock = $this->StockBooking->checkDates($stockList, $dates, $qty)))
{

//if checkedStock is an array then we have the right number in stock and available.
//so, lets get a price on those babies and then send this all back to the view.
$item = $this->data['Item']['id'];
$price = $this->_getPrice($item, $qty, $dates);

if(!empty($this->contents['Lineitem'])) {
$i = count($this->contents['Lineitem']);
} else $i = '0';

$this->contents['Lineitem'][$i]['id'] = String::uuid();
$this->contents['Lineitem'][$i]['item_id'] = $item;
$this->contents['Lineitem'][$i]['item_name'] = $this->data['Item']['name'];
$this->contents['Lineitem'][$i]['start_date'] = $dates['start'];
$this->contents['Lineitem'][$i]['end_date'] = $dates['end'];
$this->contents['Lineitem'][$i]['unit_price'] = $price['unit_price'];
$this->contents['Lineitem'][$i]['line_price'] = $price['cost'];
$this->contents['Lineitem'][$i]['line_deposit'] = $price['line_deposit'];
$this->contents['Lineitem'][$i]['qty'] = $price['qty'];
$this->contents['Lineitem'][$i]['line_weight'] = $this->_getWeight($item, $qty);

$this->contents['General']['cart_value'] = array_sum(Set::classicExtract($this->contents,
'Lineitem.{n}.line_price'));
$this->contents['General']['cart_deposits'] = array_sum(Set::classicExtract($this-
>contents, 'Lineitem.{n}.line_deposit'));

$this->contents['General']['cart_weight'] = array_sum(Set::classicExtract($this->contents,
'Lineitem.{n}.line_weight'));

$starts = array_unique(Set::classicExtract($this->contents, 'Lineitem.{n}.start_date'));


$noStarts = count($starts);
$satStart = 0;

foreach ($starts as $key => $val) :


if(date('D', $val) == 'Sat') {
$satStart++;
}
endforeach;

$this->contents['General']['satStart'] = $satStart;
$this->contents['General']['noStarts'] = $noStarts;

$noEnds = count(array_unique(Set::classicExtract($this->contents, 'Lineitem.


{n}.end_date')));
$this->contents['General']['noEnds'] = $noEnds;
//$shipCost = $this->Shipping->estimateShipping($this->contents['General']
['cart_weight'], $noStarts, $noEnds, $satStart);

$this->render('added');

} else {
$this->render('failure');
}

//$this->_prd($checkedStock);
} else {
$this->render('already_there');
}

}
function update() {

if(!$this->_checkUnique()) {

//$this->_prd($this->data);

$stuff = $this->_prepRow();
$oldQty = $stuff['old_qty'];
$i = $stuff['key'];
//$this->_prd($i);
if($this->data['StockBooking']['qty'] == '0') {
if(!empty($this->contents['Lineitem'])) {
$this->set('cart', $this->contents);
$this->Session->setFlash("Your order has been updated");
$this->render('cart');
//exit();
} else {
$this->Session->setFlash("Your order has been updated");
$this->render('no_cart');
//exit();
}
} else {

$start = $this->data['Date']['start'];
$end = $this->data['Date']['end'];

$qty = $this->data['StockBooking']['qty'];

//now lets go through the booking working out where the ship date and return dates will fall.
//NB NO COLLECTION AT THE WEEKEND OR BANKHOLIDAY so no need to
calculate shipback date.

$dates = $this->_calculateDates($start, $end);

//now we have our dates array then we need to turn that into something that we can use to
check the stock with.
//lets keep this in the StockBooking model for now, it makes most sense that way!

//first lets get a stocklist for that item.

$conditions = array(
'conditions' => array(
'Stock.item_id' => $this->data['Item']['id'],
'Stock.active' => '1',
));
$this->Item->Stock->contain();
$stockList = $this->Item->Stock->find('all', $conditions);
unset($conditions);

//then we work out which ones have got bookings and which ones don't
if(is_array($checkedStock = $this->StockBooking->checkDates($stockList, $dates, $qty)))
{

//if checkedStock is an array then we have the right number in stock and available.
//so, lets get a price on those babies and then send this all back to the view.
$item = $this->data['Item']['id'];
$price = $this->_getPrice($item, $qty, $dates);

$this->contents['Lineitem'][$i]['id'] = $this->data['Lineitem']['id'];
$this->contents['Lineitem'][$i]['item_id'] = $item;
$this->contents['Lineitem'][$i]['item_name'] = $this->data['Item']['name'];
$this->contents['Lineitem'][$i]['start_date'] = $dates['start'];
$this->contents['Lineitem'][$i]['end_date'] = $dates['end'];
$this->contents['Lineitem'][$i]['unit_price'] = $price['unit_price'];
$this->contents['Lineitem'][$i]['line_price'] = $price['cost'];
$this->contents['Lineitem'][$i]['line_deposit'] = $price['line_deposit'];
$this->contents['Lineitem'][$i]['qty'] = $price['qty'];
$this->contents['Lineitem'][$i]['line_weight'] = $this->_getWeight($item, $qty);

$this->contents['General']['cart_value'] = array_sum(Set::classicExtract($this->contents,
'Lineitem.{n}.line_price'));
$this->contents['General']['cart_deposits'] = array_sum(Set::classicExtract($this-
>contents, 'Lineitem.{n}.line_deposit'));

$this->contents['General']['cart_weight'] = array_sum(Set::classicExtract($this->contents,
'Lineitem.{n}.line_weight'));

$starts = array_unique(Set::classicExtract($this->contents, 'Lineitem.{n}.start_date'));


$noStarts = count($starts);
$satStart = 0;
foreach ($starts as $key => $val) :
if(date('D', $val) == 'Sat') {
$satStart++;
}
endforeach;
$this->contents['General']['satStart'] = $satStart;
$this->contents['General']['noStarts'] = $noStarts;

$noEnds = count(array_unique(Set::classicExtract($this->contents, 'Lineitem.


{n}.end_date')));
$this->contents['General']['noEnds'] = $noEnds;
//$shipCost = $this->Shipping->estimateShipping($this->contents['General']
['cart_weight'], $noStarts, $noEnds, $satStart);
$this->Session->setFlash("Your order has been updated");
$this->set('cart', $this->contents);
$this->render('cart');

} else {
$item = $this->data['Item']['id'];
$price = $this->_getPrice($item, $oldQty, $dates);

//if(!empty($this->contents['Lineitem'])) {
// $i = count($this->contents['Lineitem']);
//} else $i = '0';

$this->contents['Lineitem'][$i]['id'] = String::uuid();
$this->contents['Lineitem'][$i]['item_id'] = $item;
$this->contents['Lineitem'][$i]['item_name'] = $this->data['Item']['name'];
$this->contents['Lineitem'][$i]['start_date'] = $dates['start'];
$this->contents['Lineitem'][$i]['end_date'] = $dates['end'];
$this->contents['Lineitem'][$i]['unit_price'] = $price['unit_price'];
$this->contents['Lineitem'][$i]['line_price'] = $price['cost'];
$this->contents['Lineitem'][$i]['line_deposit'] = $price['line_deposit'];
$this->contents['Lineitem'][$i]['qty'] = $price['qty'];
$this->contents['Lineitem'][$i]['line_weight'] = $this->_getWeight($item, $qty);

$this->contents['General']['cart_value'] = array_sum(Set::classicExtract($this->contents,
'Lineitem.{n}.line_price'));
$this->contents['General']['cart_deposits'] = array_sum(Set::classicExtract($this-
>contents, 'Lineitem.{n}.line_deposit'));

$this->contents['General']['cart_weight'] = array_sum(Set::classicExtract($this->contents,
'Lineitem.{n}.line_weight'));

$starts = array_unique(Set::classicExtract($this->contents, 'Lineitem.{n}.start_date'));


$noStarts = count($starts);
$satStart = 0;
foreach ($starts as $key => $val) :
if(date('D', $val) == 'Sat') {
$satStart++;
}
endforeach;
$this->contents['General']['satStart'] = $satStart;
$this->contents['General']['noStarts'] = $noStarts;

$noEnds = count(array_unique(Set::classicExtract($this->contents, 'Lineitem.


{n}.end_date')));
$this->contents['General']['noEnds'] = $noEnds;
//$shipCost = $this->Shipping->estimateShipping($this->contents['General']
['cart_weight'], $noStarts, $noEnds, $satStart);
$this->Session->setFlash("Sorry, we don't have the stock to be able to do that.");
$this->set('cart', $this->contents);
$this->render('cart');
}

//$this->_prd($checkedStock);
}
}
}

function destroy() {
if($this->data['Cart']['destroy'] == 1) {
$id = $this->Session->read('Cart.id');
$this->Cart->id = $id;
$this->Cart->set('state', 'discarded');
$this->Cart->save();
unset($this->contents);
$this->Session->delete('Cart.id');
}
$this->render('no_cart');
}

function getShipOptions() {
if(!empty($this->data)) {

$postcode = $this->_getUsefulBit($this->data['ShippingPostcode']['postcode']);

if($price = $this->ShippingPriceModel->ShippingPostcode-
>findAllByPostcode($postcode)) {
foreach($price as $item) :

$conditions['OR'] = array();
$conditions['OR'][]['ShippingPriceModel.id'] = $item['ShippingPostcode']
['shipping_price_model_id'];

endforeach;

$shipModels = $this->ShippingPriceModel->find('list', array('conditions' =>


$conditions));
$this->set('ids', $shipModels);

//$this->_prd($shipModels);
} else {
if($this->contents['General']['satStart'] > '0') {
$conditions = array(
'conditions' => array(
'ShippingPriceModel.default' => '1',
'ShippingPriceModel.name' => 'Saturday',
),);
} else {
$conditions = array(
'conditions' => array(
'ShippingPriceModel.default' => '1',
'ShippingPriceModel.name !=' => 'Saturday',
),);
}
$shipModels = $this->ShippingPriceModel->find('list', $conditions);
$this->set('ids', $shipModels);
//$this->_prd($shipModels);
}
}
}

function calculateShipping() {
if(!empty($this->data)) {
//$this->_prd($this->data);
$shipModel = $this->ShippingPriceModel->findById($this->data['ShippingPriceModel']
['Id']);

$settings['max_weight'] = $shipModel['ShippingPriceModel']
['conseignment_max_ship_weight'];
$settings['over_weight_cost'] = $shipModel['ShippingPriceModel']['over_weight_cost'];
$settings['conseignment_cost'] = $shipModel['ShippingPriceModel']['conseignment_cost'];
$settings['collection_cost'] = $shipModel['ShippingPriceModel']['collection_cost'];

$shipping['base_cost'] = $this->contents['General']['noStarts'] *
$settings['conseignment_cost'];
$shipping['max_weight'] = $this->contents['General']['noStarts'] * $settings['max_weight'];
$shipping['extra_collections'] = $this->contents['General']['noEnds'] - $this-
>contents['General']['noStarts'];
$shipping['extra_costs']['collection'] = 0;

if($shipping['extra_collections'] > 0) {
$shipping['extra_costs']['collection'] = $shipping['extra_collections'] *
$settings['collection_cost'];
}

$shipping['extra_costs']['over_weight'] = 0;

if($this->contents['General']['cart_weight'] > $shipping['max_weight']) {


$shipping['extra_costs']['over_weight'] = ($this->contents['General']['cart_weight'] -
$shipping['max_weight']) * 2 * $settings['over_weight_cost'];
}

$finalcost = $shipping['base_cost'] + array_sum($shipping['extra_costs']);

$this->contents['Shipping']['shipping_cost'] = $finalcost;
$this->contents['Shipping']['shipping_model_id'] = $this->data['ShippingPriceModel']['Id'];
$this->contents['Shipping']['shipping_model_name'] = $shipModel['ShippingPriceModel']
['name'];

$this->set('cart', $this->contents);

}
}

function startCheckout() {
$this->set('cart', $this->contents);
$this->render('checkout_step_1');
}

function chooseAddresses() {
if($this->Session->check('Auth.User.id')) {
$this->set('addresses', $this->User->UserAddress->findAllByUserId($this->Auth-
>user('id')));
$this->set('cart', $this->contents);
}
}
function userLogin() {
if($this->Session->check('Auth.User.id')) {
$this->redirect(array('controller' => 'cart', 'action' => 'chooseAddresses'), true);
}
}

function shippingInfo() {

//PRIVATE FUNCTIONS
function _getPrice($item, $qty, $dates) {

//ok, lets get the daily price and if the item uses the global discount from the Item model.
$this->Item->id = $item;
$itemDetails = $this->Item->read();

$price = $itemDetails['Item']['price'];
$discountTrue = $itemDetails['Item']['global_discount'];

//lets work out the number of days in the rental


$days = ($dates['end'] - $dates['start']) / 86400;

$minDays = Configure::read('Minilodgers.min_rental_days');

if($days < $minDays){

$days = $minDays;
}

//$this->_prd($days);

$conditions1 = array(
'conditions' => array(
'DiscountPeriod.days <=' => $days,
),
'order' => array(
'DiscountPeriod.days' => 'DESC',
),
);

App::import('Model', 'DiscountPeriod');
$DiscountPeriod = new DiscountPeriod;
$DiscountPeriod->contain();

$discounty = $DiscountPeriod->find('first', $conditions1);

//$this->_prd($discounty);
if(!empty($discounty)) {

if($discountTrue !== '1') {


$conditions = array('conditions' => array(
'ItemDiscount.active' => '1',
'ItemDiscount.item_id' => $item,
'ItemDiscount.discount_period_id' => $discounty['DiscountPeriod']
['id'],
),
);

$discounts = $this->Item->ItemDiscount->find('first', $conditions);


//$this->_prd($discounts);
$discount = $discounts['ItemDiscount'];
} else {
App::import('Model', 'Discount');
$Discount = new Discount;
$conditions = array('conditions' => array(
'Discount.active' => '1',
'Discount.discount_period_id' => $discounty['DiscountPeriod']['id'],
),
);
$discounts = $Discount->find('first', $conditions);
//$this->_prd($discounts);
$discount = $discounts['Discount'];
}
} else {
//$discount = null;
}

//$this->_prd($discounts);

$costForRental = ($days * $price * $qty);

if(!is_null($discount)) {
$costForRental = $costForRental * (1 - ($discount['discount']/100));
$rental['discount'] = $discount['discount'];
}

$rental['cost'] = $costForRental;
//$rental['discount'] = $discount;
$rental['period'] = $days;
$rental['qty'] = $qty;
$rental['unit_price'] = $rental['cost'] / $rental['qty'];
$rental['line_deposit'] = $itemDetails['Item']['deposit'] * $rental['qty'];
//$this->_prd($rental);
return $rental;
}

function _calculateDates($start, $end) {

if(date('D', $start) == 'Mon') {


$dates['dispatch'] = strtotime('last Friday', $start);
} else {
$dates['dispatch'] = strtotime('-1 day', $start);
}

if(date('D', $end) == 'Fri') {


$dates['collect'] = strtotime('next Monday', $end);
$dates['return'] = strtotime('+1 day', $dates['collect']);
} elseif (date('D', $end) == 'Thu') {
$dates['collect'] = $end;
$dates['return'] = strtotime('next Monday', $end);
} else {
$dates['collect'] = $end;
$dates['return'] = strtotime('+1 day', $end);
}

$dates['start'] = $start;
$dates['end'] = $end;

if ($start + 86400 < $end) {


$i = 0;
do {
$i++;
$start += 86400;
$dates[$i] = $start;
} while ($start + 86400 < $end);
}
asort($dates);
return $dates;
}

function _testData($data) {
//write this
return true;
}

function _checkUnique() {

if(!empty($this->contents['Lineitem'])) {

foreach($this->contents['Lineitem'] as $lineitem) :

if($lineitem['item_id'] == $this->data['Item']['id'] && $lineitem['start_date'] == $this-


>data['Date']['start'] && $lineitem['end_date'] == $this->data['Date']['end']) {
//if the item_id, start and end dates match then the item isn't unique, so we need to
adapt the existing entry.
return false;
}
endforeach;
}

return true;
//$this->_testData($this->data) && !empty($this->data
}
function _getWeight($item, $qty) {
$this->Item->id = $item;
$weight = $this->Item->field('weight');

return ($weight * $qty);


}

function _prepRow() {

$ids = Set::classicExtract($this->contents, 'Lineitem.{n}.id');

$active = array_keys($ids, $this->data['Lineitem']['id']);


//$this->_prd($active);
$data = array();

foreach($active as $key => $val) :

$data['old_qty'] = $this->contents['Lineitem'][$val]['qty'];
$data['key'] = $val;

//unset($this->contents['Lineitem'][$val]);
endforeach;
return $data;
}

function _getUsefulBit($postcode) {
$testExplode = explode(' ', $postcode, 2);
if(count($testExplode) == 2) {
return $testExplode['0'];
} else {
switch(strlen($postcode)):
case 5:
$string = str_split($postcode, 2);
return $string['0'];
break;
case 6:
$string = str_split($postcode, 3);
return $string['0'];
break;
case 7:
$string = str_split($postcode, 4);
return $string['0'];
break;
endswitch;
}

//CLEANUP FUNCTIONS
function afterFilter() {

parent::afterFilter();
if(!empty($this->contents['Lineitem'])) {
$this->contents['General']['timestamp'] = strtotime('now');
if($this->Session->check('Cart.id')) $this->contents['General']['cart_id'] = $this-
>Session->read('Cart.id');
$cart['Cart']['contents'] = serialize($this->contents);
if($this->Auth->user('id')) {
$cart['Cart']['user_id'] = $this->Auth->user('id');
}
if(!is_null($this->Session->read('Cart.id'))) {
$this->Cart->id = $this->Session->read('Cart.id');
$this->Cart->save($cart);
//$this->Session->setFlash('Cart already existed and was read from the Session, all
worked well');
} else {
$cart['Cart']['timestamp'] = strtotime('now');
$cart['Cart']['state'] = 'open';
$cart['Cart']['ip'] = $this->RequestHandler->getClientIP();
$this->Cart->create();
$this->Cart->save($cart);
$this->Session->write('Cart.id', $this->Cart->id);
//$this->Session->setFlash("Couldn't find a cart to update, so just saved another one,
hope you don't mind!");
}
} else {
//$this->_prd($this->contents);
//$this->Session->setFlash('Nothing to save this time');
}
}
}
?>
<?php
class CategoriesController extends AppController {

var $name = 'categories';

//var $scaffold;

function display($id = null) {

if(!$id)
{
$this->redirect(array('controller' => 'site', 'action' => 'display'), true);
}
else
{
$this->Category->contain('Item.active = "1"');
$category = $this->Category->findById($id);
$this->set('category', $category);
$this->render('new');
}
}
function admin_add() {
if(!empty($this->data)) {
$this->Category->create();
if($this->Category->save($this->data)) {
$this->Session->setFlash('Category '.$this->data['Category']['name'].' Created',
'flash_success');
} else {
$this->Session->setFlash("Couldn't create Category, sorry", 'flash_error');
}
$this->redirect($this->referer());
}
}

function admin_display($id = null) {


$this->Category->recursive = 2;
$this->set('category', $this->Category->findById($id));
}

function admin_edit($id = null) {


if(!empty($this->data)) {
$this->Category->id = $this->data['Category']['id'];
$this->Category->save($this->data);
} else {
$this->data = $this->Category->read(null, $id);
$categoryname = $this->data['Category']['name'];
$this->set('categoryname', $categoryname);
}
}

function admin_suspend($id = null) {


if($id) {
$this->Category->id = $id;
$dt['Category']['active'] = 0;
if($this->Category->save($dt)) {
$this->Session->setFlash('Category suspended', 'flash_success');
} else {
$this->Session->setFlash('Could not suspend Category', 'flash_error');
}
$this->redirect($this->referer());
}
}

function admin_activate($id = null) {


if($id) {
$this->Category->id = $id;
$dt['Category']['active'] = 1;
if($this->Category->save($dt)) {
$this->Session->setFlash('Category activated', 'flash_success');
} else {
$this->Session->setFlash('Could not activate Category', 'flash_error');
}
$this->redirect($this->referer());
}
}
}
?>
<?php
class DepartmentsController extends AppController {

var $name = 'Departments';

//var $scaffold;

function beforeFilter() {
parent::beforeFilter();
}

function display($id = null) {

$department = $this->Department->findById($id);

$this->set('department', $department);
}

function admin_index() {
$this->set('departments', $this->Department->find('all'));
}

function admin_display($id = null) {


$this->Department->recursive = 2;
$department = $this->Department->findById($id);

$this->set('department', $department);
}

function admin_add() {

}
}

?>
<?php
class InstantPaymentNotificationsController extends AppController {
/**
* name
*
* Name of this controller class
*
* @var $name string
* @access public
*/
var $name = 'InstantPaymentNotifications';
function process(){
//Have we been sent an IPN here...
if(!empty($_POST)){
//...we have so add 'cmd' 'notify-validate' to a transaction variable
$transaction = 'cmd=<em>notify-validate';
//and add everything paypal has sent to the transaction
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$transaction .= "&$key=$value";
}
//create headers for post back
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($transaction) . "\r\n\r\n";
//If this is a sandbox transaction then 'test_ipn' will be set to '1'
if(isset($_POST['test_ipn'])){
$server = 'www.sandbox.paypal.com';
}else{
$server = 'www.paypal.com';<br>
}
//and post the transaction back for validation
$fp = fsockopen ('ssl://'.$server, 443, $errno, $errstr, 30);
//Check we got a connection and response...
if (!$fp) {
//...didn't get a response so log error in error logs
$this->log('HTTP Error in InstantPaymentNotifications::process while posting back to
PayPal: Transaction='.$transaction);
}else{
//...got a response, so we'll through the response looking for VERIFIED or INVALID
fputs ($fp, $header . $transaction);
while (!feof($fp)) {
$response = fgets ($fp, 1024);
if (strcmp ($response, "VERIFIED") == 0) {
//The response is VERIFIED so format the $_POST for processing
$notification = array();
$notification['InstantPaymentNotification']=$_POST;
$this->InstantPaymentNotification->save($notification);
$this->/</em>_processTransaction($this->InstantPaymentNotification->id);<br>
}else if (strcmp ($response, "INVALID") == 0) {
//The response is INVALID so log it for investigation
$this->log('Found Invalid:'.$transaction);
}
}
fclose ($fp);
}
}
//Redirect
$this->redirect('/');
}
function __processTransaction($txnId){
//Here is where you can implement code to apply the transaction to your system
//for example, you could now mark an order as paid, create a subscription, just
//retrieve the transaction using the txn_id passed and apply whatever logic your site
//needs.
}
}
?>
<?php
class ItemsController extends AppController {

var $name = 'Items';

//var $scaffold;

function display($id = null) {


//$this->_prd($this->Session->read());
$this->Item->contain();
$this->Item->id = $id;
$item = $this->Item->read();

$data = $this->_getPriceAndDiscount($id);

$minPrice = $data['Price'] * (1 - ($data['Discount']/100));


$discount = $data['Discount'];

$i = '0';
$quantity = array();
while ($i++ < 10) {
$quantity[$i] = $i;
}

$this->set(compact('item', 'price', 'discounts', 'minPrice', 'quantity'));


$this->render('display');
}

function _getPriceAndDiscount($input) {

$this->Item->id = $input;
$item = $this->Item->read();

$price = $item['Item']['price'];
if($item['Item']['global_discount'] !== '1') {

$conditions = array('conditions' => array(


'ItemDiscount.active' => '1',
'ItemDiscount.item_id' => $input,
),
'order' => array('ItemDiscount.discount' => 'DESC'),
);

$discounts = $this->Item->ItemDiscount->find('first', $conditions);

} else {
App::import('Model', 'Discount');
$Discount = new Discount;
$conditions = array('conditions' => array(
'Discount.active' => '1',
),
'order' => array('Discount.discount' => 'DESC'),
);
$discounts = $Discount->find('first', $conditions);
}

$data['Discount'] = $discounts['Discount']['discount'];
$data['Price'] = $price;

return $data;

function admin_add() {

if(!empty($this->data)) {
$this->Item->create();
if($this->Item->save($this->data)) {
$this->Session->setFlash('Item '.$this->data['Item']['name'].' Created', 'flash_success');
} else {
$this->Session->setFlash("Couldn't create Item, sorry", 'flash_error');
}
$this->redirect($this->referer());
}
}

function admin_display($id = null) {


$this->Item->recursive = 2;
$this->set('item', $this->Item->findById($id));
}

function admin_edit($id = null) {


if(!empty($this->data)) {
$this->Item->id = $this->data['Item']['id'];
$this->Item->save($this->data);
} else {
$this->data = $this->Item->read(null, $id);
$categoryname = $this->data['Item']['name'];
$this->set('itemname', $itemname);
}
}

function admin_suspend($id = null) {


if($id) {
$this->Item->id = $id;
$dt['Item']['active'] = 0;
if($this->Item->save($dt)) {
$this->Session->setFlash('Item suspended', 'flash_success');
} else {
$this->Session->setFlash('Could not suspend Item', 'flash_error');
}
$this->redirect($this->referer());
}
}

function admin_activate($id = null) {


if($id) {
$this->Item->id = $id;
$dt['Item']['active'] = 1;
if($this->Item->save($dt)) {
$this->Session->setFlash('Item activated', 'flash_success');
} else {
$this->Session->setFlash('Could not activate Item', 'flash_error');
}
$this->redirect($this->referer());
}
}
}
?>
<?php
/*
* Mercury Rental Cart for CakePHP
* copyright John Maxwell 2010
* all rights very much reserved indeed
* so don't copy it, or else!
* john@jgwmaxwell.com OR jgwmaxwell.com
*/
class CartController extends AppController {

var $name = 'Cart';

var $uses = array('Cart', 'Item');

var $cartExists = null;

function beforefilter() {
if(is_array($cart = $this->_checkCart())) {
$this->cartExists = true;
} else {
$this->cartExists = false;
}
}

function index() {
//display the shopping cart
if($this->cartExists) {
$this->set('cart', $cart);
$this->render('cart');
} else {
$this->render('no_cart');
}
}
function checkItem() {

if($this->_testData($this->data) && !empty($this->data)) {

//using the dates input, firstly make them useful, then compare them to the cookie - update
cookie if required.

$start = strtotime($this->data['Date']['start']);
$end = strtotime($this->data['Date']['end']);

$qty = $this->data['StockBooking']['qty'];

//now lets go through the booking working out where the ship date and return dates will fall.
//NB NO COLLECTION AT THE WEEKEND OR BANKHOLIDAY so no need to
calculate shipback date.

$dates = $this->_calculateDates($start, $end);

//now we have our dates array then we need to turn that into something that we can use to
check the stock with.
//lets keep this in the StockBooking model for now, it makes most sense that way!

//first lets get a stocklist for that item.

$conditions = array(
'conditions' => array(
'Stock.item_id' => $this->data['Item']['id'],
'Stock.active' => '1',
));
$this->Item->Stock->contain();
$stockList = $this->Item->Stock->find('all', $conditions);
unset($conditions);

//then we work out which ones have got bookings and which ones don't
if(is_array($checkedStock = $this->Item->Stock->StockBooking->checkDates($stockList,
$dates, $qty))) {

//if checkedStock is an array then we have the right number in stock and available.
//so, lets get a price on those babies and then send this all back to the view.
$item = $this->data['Item']['id'];
$price = $this->_getPrice($item, $qty, $dates);

$this->set('price', $price);
$this->set('number', $checkedStock);

$form['Date.start'] = $this->data['Date']['start'];
$form['Date.end'] = $this->data['Date']['end'];
$form['StockBooking.qty'] = $checkedStock;
$form['Item.id'] = $this->data['Item']['id'];
$form['Item.name'] = $this->data['Item']['name'];

$this->set('form', $form);
$this->render('success');

} elseif ($checkedStock > 0) {


$item = $this->data['Item']['id'];
$price = $this->_getPrice($item, $checkedStock, $dates);

$this->set('price', $price);
$this->set('number', $checkedStock);

$form['Date.start'] = $this->data['Date']['start'];
$form['Date.end'] = $this->data['Date']['end'];
$form['StockBooking.qty'] = $checkedStock;
$form['Item.id'] = $this->data['Item']['id'];
$form['Item.name'] = $this->data['Item']['name'];

$this->set('form', $form);
$this->render('partial_success');
} else {
$this->render('failure');
}

//$this->_prd($checkedStock);
}
}

function add() {

if(!$cartExists) {

$this->_makeCart();
}

if($this->_testData($this->data) && !empty($this->data)) {

//using the dates input, firstly make them useful, then compare them to the cookie - update
cookie if required.

$start = strtotime($this->data['Date']['start']);
$end = strtotime($this->data['Date']['end']);

$qty = $this->data['StockBooking']['qty'];

$this->_storeDates($start, $end);

//now lets go through the booking working out where the ship date and return dates will fall.
//NB NO COLLECTION AT THE WEEKEND OR BANKHOLIDAY so no need to
calculate shipback date.

$dates = $this->_calculateDates($start, $end);

//now we have our dates array then we need to turn that into something that we can use to
check the stock with.
//lets keep this in the StockBooking model for now, it makes most sense that way!

//first lets get a stocklist for that item.


$conditions = array(
'conditions' => array(
'Stock.item_id' => $this->data['Item']['id'],
'Stock.active' => '1',
));
$this->Item->Stock->contain();
$stockList = $this->Item->Stock->find('all', $conditions);
unset($conditions);

//then we work out which ones have got bookings and which ones don't
if(is_array($checkedStock = $this->Item->Stock->StockBooking->checkDates($stockList,
$dates, $qty))) {

//if checkedStock is an array then we have the right number in stock and available.
//so, lets get a price on those babies and then send this all back to the view.

$item = $this->data['Item']['id'];
$price = $this->_getPrice($item, $qty, $dates);

$readyToSave = $this->_doPrepForCart($item, $price, $qty, $dates, $checkedStock);

if($this->_saveCart($readyToSave))

$this->render('added');

} else {
$this->render('not_added');
}

//$this->_prd($checkedStock);
}
}

function _getPrice($item, $qty, $dates) {

//ok, lets get the daily price and if the item uses the global discount from the Item model.
$this->Item->id = $item;
$itemDetails = $this->Item->read();

$price = $itemDetails['Item']['price'];
$discountTrue = $itemDetails['Item']['global_discount'];

//lets work out the number of days in the rental


$days = ($dates['end'] - $dates['start']) / 86400;

$minDays = Configure::read('Globalprefs.min_rental_days');

if($days < $minDays){


$days = $minDays;
}

$conditions1 = array(
'conditions' => array(
'DiscountPeriod.days <' => $days,
),
'order' => array(
'DiscountPeriod.days' => 'DESC',
),
);

App::import('Model', 'DiscountPeriod');
$DiscountPeriod = new DiscountPeriod;
$DiscountPeriod->contain();

$discounty = $DiscountPeriod->find('first', $conditions1);

//$this->_prd($discounty);
if(!empty($discounty)) {

if($discountTrue !== '1') {

$conditions = array('conditions' => array(


'ItemDiscount.active' => '1',
'ItemDiscount.item_id' => $item,
'ItemDiscount.discount_period_id' => $discounty['DiscountPeriod']
['id'],
),
);

$discounts = $this->Item->ItemDiscount->find('first', $conditions);


//$this->_prd($discounts);
$discount = $discounts['ItemDiscount'];
} else {
App::import('Model', 'Discount');
$Discount = new Discount;
$conditions = array('conditions' => array(
'Discount.active' => '1',
'Discount.discount_period_id' => $discounty['DiscountPeriod']['id'],
),
);
$discounts = $Discount->find('first', $conditions);
//$this->_prd($discounts);
$discount = $discounts['Discount'];
}
} else {
//$discount = null;
}

//$this->_prd($discounts);
$costForRental = ($days * $price * $qty);

if(!is_null($discount)) {
$costForRental = $costForRental * (1 - ($discount['discount']/100));
$rental['discount'] = $discount['discount'];
}

$rental['cost'] = $costForRental;
//$rental['discount'] = $discount;
$rental['period'] = $days;
$rental['qty'] = $qty;
$rental['unit_price'] = $rental['cost'] / $rental['qty'];
//$this->_prd($rental);
return $rental;
}

function _calculateDates($start, $end) {

if(date('D', $start) == 'Mon') {


$dates['dispatch'] = strtotime('last Friday', $start);
} else {
$dates['dispatch'] = strtotime('-1 day', $start);
}

if(date('D', $end) == 'Fri') {


$dates['collect'] = strtotime('next Monday', $end);
$dates['return'] = strtotime('+1 day', $dates['collect']);
} elseif (date('D', $end) == 'Thu') {
$dates['collect'] = $end;
$dates['return'] = strtotime('next Monday', $end);
} else {
$dates['collect'] = $end;
$dates['return'] = strtotime('+1 day', $end);
}

$dates['start'] = $start;
$dates['end'] = $end;

if ($start + 86400 < $end) {


$i = 0;
do {
$i++;
$start += 86400;
$dates[$i] = $start;
} while ($start + 86400 < $end);
}
asort($dates);
return $dates;
}

function _checkCart() {
if(!$this->Session->check('Mercury')) {
return $this->_recoverCart();
} else {
return $this->Session->read('Mercury');
}
}

function _recoverCart() {
if(!is_null($mercuryId = $this->Cookie->read('Mercury.id'))) {
$this->Cart->id = $mercuryId;
$cartContents = unserialize($this->Cart->field('contents'));
return $cartContents;
} else {
$cart['Cart']['contents'] = null;
$cart['Cart']['date'] = strtotime('now');
$cart['Cart']['user_id'] = null;
if($this->Session->check('Auth.User.id')) {
$cart['Cart']['user_id'] = $this->Session->read('Auth.User.id');
}

$this->Cart->create();
if($this->Cart->save($cart)) {
$id = $this->Cart->id;
$this->Cookie->write('Mercury.id', $id);
$contents['Cart'] = $cart['Cart'];
$contents['Cart']['id'] = $id;
$contents['Cart']['Lineitem'] = null;
return $contents;
}
}
}

function _testData($data) {
//write this
return true;
}

function _storeDates($start, $end) {


//write this
$oldStart = $this->Cookie->read('Site.start_date');
$oldEnd = $this->Cookie->read('Site.end_date');

if($start !== $oldStart) {


$this->Cookie->delete('Site.start_date');
$this->Cookie->write('Site.start_date', $start);
}

if($end !== $oldEnd) {


$this->Cookie->delete('Site.start_date');
$this->Cookie->write('Site.end_date', $end);
}
}
function _makeDatesReadyForDb($dates) {

$date = array();

foreach ($dates as $key => $val) :

$date[]['date'] = date('Y-m-d', $val);


if(!is_numeric($key)) {
$date[]['is_'.$key] = '1';
}
endforeach;
return $date;
}

function _doPrepForCart($itemId, $price, $qty, $dates, $checkedStock) {

$cart = $this->Session->read('Mercury.Cart');

$lineitem = $cart['Lineitem'];

$this->Item->id = $itemId;
$itemName = $this->Item->field('name');

$this->Item->id = $itemId;
$itemDeposit = $this->Item->field('deposit');

$store['dates'] = serialize($dates);
$store['checkedStock'] = serialize($checkedStock);

$store = serialize($store);

$lineitem[]['id'] = String::uuid();
$lineitem[]['item_id'] = $itemId;
$lineitem[]['item_name'] = $itemName;
$lineitem[]['start_date'] = date('Y-m-d', $dates['start']);
$lineitem[]['end_date'] = date('Y-m-d', $dates['end']);
$lineitem[]['qty'] = $qty;
$lineitem[]['line_price'] = $price['cost'];
$lineitem[]['line_deposits'] = $itemDeposit * $qty;
$lineitem[]['store'] = $store;

return $lineitem;

function _saveCart($lineitem) {
$now = strtotime('now');
$this->Session->write('Mercury.Cart.date', strtotime('now'));

$cartvalue = null;
$cartdeposit = null;
foreach($lineitem as $item) :

$cartvalue = $cartvalue + $lineitem['line_price'];


$cartdeposit = $cartvalue + $lineitem['line_deposits'];
endforeach;

$this->Session->delete('Mercury.Cart.Lineitem');
$this->Session->write('Mercury.Cart.Lineitem', $lineitem);
$this->Session->write('Mercury.Cart.value', $cartvalue);
$this->Session->write('Mercury.Cart.deposit', $cartdeposit);

$compactCart = serialize($this->Session->read('Mercury.Cart'));

$cart['Cart']['user_id'] = null;

if($this->Session->check('Auth.User')) {
$cart['Cart']['user_id'] = $this->Session->read('Auth.User.id');
}

$cart['Cart']['timestamp'] = strtotime('now');
$cart['Cart']['contents'] = $compactCart;

$this->Cart->id = $this->Session->read('Mercury.Cart.id');
if($this->Cart->save($cart))

return true;
}

}
<?php
class CartController extends AppController {

var $name = 'Cart';

var $uses = array('StockBooking', 'Cart');

var $contents = null;

function destroy() {
$this->Session->destroy();
$this->Cookie->destroy();
$this->redirect(array('controller' => 'cart', 'action' => 'index'));
}

function _loadCart() {
if(!is_null($this->Cookie->read('Cart.id'))) {
$this->Cart->id = $this->Cookie->read('Cart.id');
//$this->_prd($id);
$cart = $this->Cart->read();
$this->contents = unserialize($cart['Cart']['contents']);
$this->_prd($this->Cart->read());
} else {
//$this->_prd($this->Cookie->read());
$this->_makeCart();
}
}

function beforeFilter() {
$this->_loadCart();

//$this->_prd($this->Cookie->read());
}

function index() {
if(!empty($this->contents)) {
$this->set('cart', $this->contents);
$this->render('cart');
} else {
$this->render('no_cart');
}
}

function _makeCart() {
$cart['Cart']['timestamp'] = strtotime('now');
$cart['Cart']['state'] = 'open';
$cart['Cart']['ip'] = $this->RequestHandler->getClientIP();
$cart['Cart']['contents'] = null;
$cart['Cart']['user_id'] = null;

if($this->Session->check('Auth.User.id')) $cart['Cart']['user_id'] = $this->Session-


>read('Auth.User.id');

$this->Cart->create();
if($this->Cart->save($cart)) {
$id = $this->Cart->id;
//$this->_prd($id);
$this->Cookie->write('Cart.id', $id);
$this->_prd($this->Cookie->read());
}
}

/*function afterFilter() {

$cart['Cart']['contents'] = serialize($this->contents);
$cart['Cart']['timestamp'] = strtotime('now');
if($this->Session->check('Auth.User.id')) $cart['Cart']['id'] = $this->Session-
>read('Auth.User.id');

$this->Cart->id = $this->Cookie->read('Cart.id');
$this->Cart->save($cart);
} */
}
?>
<?php
class AdminController extends AppController {

var $name = 'Admin';

var $layout = 'admin';

var $uses = array('Department', 'DiscountPeriod');

var $components = array('Auth', 'Image');

function beforeFilter() {
parent::beforeFilter();
$this->Auth->fields = array(
'username' => 'email',
'password' => 'password',
);
$this->Auth->authorize = 'controller';
$this->Auth->allowedActions = array('login', 'logout', 'register');
}

function index() {

function categories($id = null) {

$this->set('department', $this->Department->findById($id));
}

function departments() {

$this->set('departments', $this->Department->find('all'));
}

function addDepartment() {
if(!empty($this->data)) {

$this->Department->create();
$this->Department->save($this->data);
$this->redirect($this->referer());
}
}

function addCategory() {

if(!empty($this->data)) {

$this->Department->Category->create();
$this->Department->Category->save($this->data);
$this->redirect($this->referer());
}
}

function editCategory() {

if(!empty($this->data) && !empty($this->data['Category']['id'])) {

$this->Department->Category->id = $this->data['Category']['id'];
$this->Department->Category->save($this->data);
$this->redirect($this->referer());
}
}

function catview($id = null) {

$this->set('category', $this->Department->Category->findById($id));
}

function itemview($id = null) {


$this->Department->Category->Item->contain();
$item = $this->Department->Category->Item->findById($id);
$this->set('item', $item);

$this->Department->Category->Item->Stock->contain();
$conditions1 = array('conditions' => array(
'Stock.active' => '1',
'Stock.item_id' => $id)
);
$this->set('activeStock', $this->Department->Category->Item->Stock->find('all',
$conditions1));

$this->Department->Category->Item->Stock->contain();
$conditions2 = array('conditions' => array(
'Stock.active' => '0',
'Stock.item_id' => $id)
);
$this->set('inactiveStock', $this->Department->Category->Item->Stock->find('all',
$conditions2));

//$discountPeriod = $this->DiscountPeriod->find('all');
if($item['Item']['global_discount'] == '0') {
$conditions = array(
'conditions' => array(
'ItemDiscount.item_id' => $id,
'ItemDiscount.active' => '1',),
);
$discounts = $this->Department->Category->Item->ItemDiscount->find('all', $conditions);
foreach($discounts as $discount) :

$itemDiscount[] = array('discount' => $discount['ItemDiscount']['discount'],


'discount_period_name' => $discount['DiscountPeriod']['name'], 'discount_period_id' =>
$discount['DiscountPeriod']['id'], 'discount_period_days' => $discount['DiscountPeriod']['days']);
endforeach;
} else {

App::import('Model', 'Discount');
$Discounts = new Discount;

$discounts = $Discounts->find('all');
foreach ($discounts as $discount) :
$itemDiscount[] = array('discount' => $discount['Discount']['discount'],
'discount_period_name' => $discount['DiscountPeriod']['name'], 'discount_period_id' =>
$discount['DiscountPeriod']['id'], 'discount_period_days' => $discount['DiscountPeriod']['days']);
endforeach;
}
$this->set('itemDiscount', $itemDiscount);

function updateItemPrice() {
if($this->data) {

}
}

function updateItemDiscount() {
if(!empty($this->data)) {
$this->Department->Category->Item->id = $this->data['ItemDiscount']['item_id'];
$uses_global = $this->Department->Category->Item->field('global_discount');

if($uses_global == '1') {
App::import('Model', 'Discount');
$Discount = new Discount;

$discounts = $Discount->find('all');

foreach($discounts as $discount) :
if($this->data['ItemDiscount']['discount_period_id'] == $discont['Discount']
['discount_period_id']) {

$item['ItemDiscount'][] = array(
'item_id' => $this_data['ItemDiscount']['item_id'],
'discount_period_id' => $discount['Discount']['discount_period_id'],
'discount' => $this->data['ItemDiscount']['discount'],
'start_date' => date('Y-m-d', strtotime('now')),
'active' => 1,
);
} else {

$item['ItemDiscount'][] = array(
'item_id' => $this_data['ItemDiscount']['item_id'],
'discount_period_id' => $discount['Discount']['discount_period_id'],
'discount' => $discount['Discount']['discount'],
'start_date' => date('Y-m-d', strtotime('now')),
'active' => 1,
);
}

endforeach;

$this->Department->Category->Item->ItemDiscount->create();
$this->Department->Category->Item->ItemDiscount->save($item);

unset($item);

$item['Item']['global_discount'] = 0;

$this->Department->Category->Item->id = $this->data['ItemDiscount']['item_id'];
$this->Department->Category->Item->save($item);

if($item['Item']['global_discount'] == '0') {
$conditions = array(
'conditions' => array(
'ItemDiscount.item_id' => $id,
'ItemDiscount.active' => '1',),
);
$discounts = $this->Department->Category->Item->ItemDiscount->find('all',
$conditions);
foreach($discounts as $discount) :

$itemDiscount[] = array('discount' => $discount['ItemDiscount']['discount'],


'discount_period_name' => $discount['DiscountPeriod']['name'], 'discount_period_id' =>
$discount['DiscountPeriod']['id'], 'discount_period_days' => $discount['DiscountPeriod']['days']);
endforeach;
} else {

App::import('Model', 'Discount');
$Discounts = new Discount;

$discounts = $Discounts->find('all');
foreach ($discounts as $discount) :
$itemDiscount[] = array('discount' => $discount['Discount']['discount'],
'discount_period_name' => $discount['DiscountPeriod']['name'], 'discount_period_id' =>
$discount['DiscountPeriod']['id'], 'discount_period_days' => $discount['DiscountPeriod']['days']);
endforeach;
}
$this->set('itemDiscount', $itemDiscount);
$this->set('item', $this->Department->Category->Item->findById($this-
>data['ItemDiscount']['item_id']));

} else {
//if it doesn't use the global discounting structure
}
}
}

function addItem() {

if(!empty($this->data)) {

$this->Department->Category->Item->create();
$this->Department->Category->Item->save($this->data);
$this->redirect($this->referer());
}
}

function editItem() {

if(!empty($this->data) && !empty($this->data['Item']['id'])) {

$this->Department->Category->Item->id = $this->data['Item']['id'];
$this->Department->Category->Item->save($this->data);
$this->redirect($this->referer());
}
}

function control($type = null, $id = null, $action = null) {

if(!empty($type) && !empty($id) && !empty($action)) {

if($action == 'activate') {
$control = 1;
} else {
$control = 0;
}

switch($type) :
case 'item':
$this->Department->Category->Item->id = $id;
$this->Department->Category->Item->set('active', $control);
$this->Department->Category->Item->save();
//echo "item";
//die();
break;
case 'stock':
$data['Stock']['active'] = $control;
$this->Department->Category->Item->Stock->id = $id;
$this->Department->Category->Item->Stock->save($data);
//echo "stock";
//die();
break;
endswitch;
}
$this->redirect($this->referer());
}
function addStock() {

if(!empty($this->data)) {

//$this->_prd($this->data);
$this->Department->Category->Item->Stock->create();

if($this->Department->Category->Item->Stock->save($this->data)) {

$this->Session->setFlash('Stock Added');
$this->redirect($this->referer());
} else {
echo "nope, didn't work!";
die();
}
} else {
echo "empty";
die();
}
}

function addPhoto() {

$data['Item']['image_path'] = $this->Image->upload_image_and_thumbnail($this-
>data['Image']['upload'],375,375,150,150,"products");
//$this->_prd($this->data);
$this->Department->Category->Item->id = $this->data['Item']['id'];
$this->Department->Category->Item->save($data);

$this->redirect($this->referer());
}

function deletePhoto() {

if(!empty($this->data)) {
$data['Item']['image_path'] = null;
$this->Department->Category->Item->id = $this->data['Item']['id'];
if($this->Department->Category->Item->save($data)) {

$this->Image->delete_image($this->data['Item']['image_path'], 'products');
}
}

$this->redirect($this->referer());
}

function discounts() {
App::import('Model', 'DiscountPeriod');
$DiscountPeriod = new DiscountPeriod;

$conditions = array('conditions' => array(


'DiscountPeriod.active' => 1,
));
$discountPeriods = $DiscountPeriod->find('all', $conditions);
//$this->_prd($discountPeriods);
$this->set('discountPeriods', $discountPeriods);
}

function isAuthorized() {
if($this->Session->read('Auth.User.role') == 'admin') {

return true;
} else {

return false;
}
}
}
?>
<?php
class CartController extends AppController {

var $name = 'Cart';

var $uses = array('StockBooking', 'Cart');

function beforeFilter() {
//$this->Session->destroy();
//$this->Cookie->destroy();
//$this->_checkCart();
//$this->_prd($this->Session->read());
//$this->_prd($this->Cookie->read());
//$this->_resetDates();
//$this->_prd($this->data);
}

function index() {
//$this->_prd($this->Session->read('Mercury'));
//lets try and find the cart and see where that cart is living, if there is one!

if(!$this->Session->check('Mercury')) {
$packSession = $this->Cookie->read('Mercury');
//$this->_prd($packSession);
if(is_null($packSession)) {
$this->render('no_cart');
} else {
$cart['Cart'] = $packSession['Cart'];
$cart['Lineitem'] = unserialize($packSession['Lineitem']);
$this->set('cart', $cart);
$this->render('cart');
}
} else {
$cart = $this->Session->read('Mercury');
$this->set('cart', $cart);
$this->render('cart');
}

$this->render('no_cart');
}

function add() {
if(!empty($this->data)){
// get the dates array for the requested booking.
$dates = $this->StockBooking->calculateDates($this->data['StockBooking']);

//check the dates to see how they compare.


//step 1 get active stocks of the right type
$conditions = array(
'conditions' => array(
'Stock.active' => '1',
'Stock.item_id' => $this->data['StockBooking']['itemId'],
),
);

$this->StockBooking->Stock->contain();
$activeStock = $this->StockBooking->Stock->find('all', $conditions);

$qty = $this->data['StockBooking']['qty'];

if(is_array($stockUnit = $this->StockBooking->checkDates($activeStock, $dates, $qty))) {

$price = $this->_getPrice($this->data['StockBooking']['startDate'], $this-


>data['StockBooking']['endDate'], $qty, $this->data['StockBooking']['itemId']);

if(!$this->_checkCart()) {
$this->_makeCart();
}

$this->StockBooking->Stock->Item->id = $this->data['StockBooking']['itemId'];
$deposit = $this->StockBooking->Stock->Item->field('deposit');
$linedeposit = $deposit * $qty;

//having established the stock is available, lets create the cart entry.
if($this->Session->check('Mercury.Lineitem')) {
$lineitem = array();
$lineitem = $this->Session->read('Mercury.Lineitem');
//$this->_prd($lineitem);
} else {

$lineitem = array();
}
$newUUID = String::uuid();
$lineitem[] = array(
'id' => $newUUID,
'cart_id' => $this->Session->read('Mercury.Cart.id'),
'item_id' => $this->data['StockBooking']['itemId'],
'item_name' => $this->data['StockBooking']['item_name'],
'blackout_date' => $dates['blackoutDate'],
'ship_date' => $dates['shipDate'],
'start_date' => $dates['startDate'],
'end_date' => $dates['endDate'],
'return_date' => $dates['returnDate'],
'period' => $price['period'],
'unit_price' => $price['unit_price'],
'unit_deposit' => $deposit,
'qty' => $qty,
'line_price' => $price['cost'],
'line_deposits' => $linedeposit,
);
$cartValue = array_sum(Set::extract('/line_price', $lineitem));
$cartDeposit = array_sum(Set::extract('/line_deposits', $lineitem));

$this->Session->write('Mercury.Lineitem', $lineitem);
$this->Session->write('Mercury.Cart.value_goods', $cartValue);
$this->Session->write('Mercury.Cart.value_deposits', $cartDeposit);

$cart_contents = serialize($this->Session->read('Mercury.Lineitem'));
$this->Cookie->delete('Mercury.Lineitem');
$this->Cookie->write('Mercury.Lineitem', $cart_contents);
//$this->Cookie->write('Mercury', $this->Session->read('Mercury'));
$this->render('added');
}
//$this->_makeLineItem($price, $stockUnit);

//$this->render('success');
} else {
echo "Shiteeee!";
}

function amend() {

if(!empty($this->data)) {

}
}

function update() {

if(!empty($this->data)) {
$savedCart = $this->Session->read('Mercury');
if($this->data['Cart']['id'] = $savedCart['Cart']['id']) {
$i = 0;
foreach ($savedCart['Lineitem'] as $array) :

if($array['id'] == $this->data['Lineitem']['id']) :
$lineId = $i;
$lineitem = $array;
endif;
$i++;
endforeach;

if(!empty($lineitem))
{
$id = $lineitem['id'];
$qty = $this->data['Lineitem']['qty'];

if($qty > $lineitem['qty']) {


//do additional stockchecking

} elseif ($qty == $lineitem['qty']) {


//no change so about the update
$this->set('cart', $this->Session->read('Mercury'));
$this->render('cart');
} else {
$linePrice = $lineitem['unit_price'] * $qty;
$lineDeposit = $lineitem['unit_deposit'] * $qty;
$this->Session->write('Mercury.Lineitem.'.$lineId.'.qty', $qty);
$this->Session->write('Mercury.Lineitem.'.$lineId.'.line_price', $linePrice);
$this->Session->write('Mercury.Lineitem.'.$lineId.'.line_deposit', $lineDeposit);
//$this->_prd($this->Session->read());
//$compactCart = serialize($this->Session->read('Mercury'));
//$this->Cookie->destroy();
//$this->Cookie->write('Mercury.Cart.id' => )
$this->set('cart', $this->Session->read('Mercury'));
$this->render('cart');
}
//$this->_prd($lineitem);
} else {
$savedCart['error'] = 'No match';
$this->_prd($savedCart);

}
} else {
$savedCart['error'] = 'Wrong id';
$this->_prd($savedCart);
}
}
$this->set('cart', $this->Session->read('Mercury'));
$this->render('cart');
}

function destroy() {

if(!$this->Session->check('Mercury') OR !$this->Cookie->read('Mercury')) {

$this->redirect($this->referer(), true);
} else {
if($this->data['Cart']['id'] == $this->Session->read('Mercury.Cart.id')) {

$trashedCart = serialize($this->Session->read('Mercury'));
$data['Cart']['id'] = $this->Session->read('Mercury.Cart.id');
if($this->Session->check('Auth.User.id')) {
$data['Cart']['user_id'] = $this->Session->read('Auth.User.id');
} else {
$data['Cart']['user_id'] = null;
}
$data['Cart']['date'] = date('Y-m-d');
$data['Cart']['contents'] = $trashedCart;

$this->Cart->create();
$this->Cart->save($data);

$this->Session->delete('Mercury');
$this->Cookie->destroy();

unset($data);

$this->render('no_cart');
}
}
}

function priceAndAvailabilityCheck() {
//$this->Session->destroy();
if($this->_checkArray($this->data)) {
$start = mktime(0,0,0,$this->data['StockBooking']['startDate']['month'],$this-
>data['StockBooking']['startDate']['day'],$this->data['StockBooking']['startDate']['year']);
$end = mktime(0,0,0,$this->data['StockBooking']['endDate']['month'],$this-
>data['StockBooking']['endDate']['day'],$this->data['StockBooking']['endDate']['year']);
if(!$this->Session->check('Cart.date.start') OR $this->Session->read('Cart.date.start') !=
$start) {
$this->Session->write('Cart.date.start', $start);
}
if(!$this->Session->check('Cart.date.end') OR $this->Session->read('Cart.date.end') !==
$end) {
$this->Session->write('Cart.date.end', $end);
}
//$start = $this->_getTimeFromDate($this->data['StockBooking']['startDate']);
//$end = $this->_getTimeFromDate($this->data['StockBooking']['endDate']);
//$this->_registerDates($start, $end);
if(!empty($this->data)){
// get the dates array for the requested booking.
$dates = $this->StockBooking->calculateDates($this->data['StockBooking']);

//check the dates to see how they compare.


//step 1 get active stocks of the right type
$conditions = array(
'conditions' => array(
'Stock.active' => '1',
'Stock.item_id' => $this->data['StockBooking']['itemId'],
),
);

$this->StockBooking->Stock->contain();
$activeStock = $this->StockBooking->Stock->find('all', $conditions);

$qty = $this->data['StockBooking']['qty'];

if(is_array($stockUnit = $this->StockBooking->checkDates($activeStock, $dates, $qty))) {


//success
$price = $this->_getPrice($this->data['StockBooking']['startDate'], $this-
>data['StockBooking']['endDate'], $qty, $this->data['StockBooking']['itemId']);

$this->set('price', $price);

$form['StockBooking.startDate.day'] = $this->data['StockBooking']['startDate']['day'];
$form['StockBooking.startDate.month'] = $this->data['StockBooking']['startDate']
['month'];
$form['StockBooking.startDate.year'] = $this->data['StockBooking']['startDate']['year'];
$form['StockBooking.endDate.day'] = $this->data['StockBooking']['endDate']['day'];
$form['StockBooking.endDate.month'] = $this->data['StockBooking']['endDate']['month'];
$form['StockBooking.endDate.year'] = $this->data['StockBooking']['endDate']['year'];
$form['StockBooking.qty'] = $qty;
$form['StockBooking.itemId'] = $this->data['StockBooking']['itemId'];
$form['StockBooking.item_name'] = $this->data['StockBooking']['itemName'];

$this->set('form', $form);
$this->render('success');
} else {

if($qty >= '1') {


$price = $this->_getPrice($this->data['StockBooking']['startDate'], $this-
>data['StockBooking']['endDate'], $stockUnit, $this->data['StockBooking']['itemId']);
$this->set('price', $price);
$this->render('partial_success');
}
else {
$this->render('failure');
}
}

}
} else {
$this->render('incomplete');
}
}

function _getPrice($start, $end, $qty, $id) {


$initDay = mktime(0,0,0,$start['month'],$start['day'],$start['year']);
$endDay = mktime(0,0,0,$end['month'],$end['day'],$end['year']);

$days = ($endDay - $initDay) / 86400;

$minDays = Configure::read('Globalprefs.min_rental_days');

if($days < $minDays){

$days = $minDays;
}

$conditions = array('conditions' => array(


'OR' => array(
array(
'ItemPrice.start_date <=' => date('Y-m-d', $initDay),
'ItemPrice.end_date >' => date('Y-m-d', $endDay),
),
array(
'ItemPrice.start_date <=' => date('Y-m-d', $initDay),
'ItemPrice.end_date' => null,
),
),
'ItemPrice.active' => '1',
'ItemPrice.item_id' => $id,
));
$this->StockBooking->Stock->Item->ItemPrice->contain();
$price = $this->StockBooking->Stock->Item->ItemPrice->find('first', $conditions);

if($price['ItemPrice']['global_discount'] !== '1') {

$conditions2 = array('conditions' => array(


'OR' => array(
array(
'ItemPriceDiscount.start_date <=' => date('Y-m-d',
$initDay),
'ItemPriceDiscount.end_date >' => date('Y-m-d', $endDay),
),
array(
'ItemPriceDiscount.start_date <=' => date('Y-m-d',
$initDay),
'ItemPriceDiscount.end_date' => null,
),
),
'ItemPriceDiscount.active' => '1',
'ItemPriceDiscount.item_price_id' => $price['ItemPrice']['id'],
));

$discounts = $this->StockBooking->Stock->Item->ItemPrice->ItemPriceDiscount-
>find('all', $conditions2);
$discounts['source'] = 'Local';
} else {
App::import('Model', 'Discount');
$Discount = new Discount;
$conditions3 = array('conditions' => array(
'OR' => array(
array(
'Discount.start_date <=' => date('Y-m-d', $initDay),
'Discount.end_date >' => date('Y-m-d', $endDay),
),
array(
'Discount.start_date <=' => date('Y-m-d', $initDay),
'Discount.end_date' => null,
),
),
'Discount.active' => '1',
),
'order' => array('Discount.discount' => 'ASC'),
);
$discounts = $Discount->find('all', $conditions3);
$discounts['source'] = 'Global';
}

$discountPeriod = Set::extract('/DiscountPeriod/days', $discounts);


$discountAmount = Set::extract('/Discount/discount', $discounts);

$discountMatrix = array_combine($discountPeriod, $discountAmount);

foreach($discountMatrix as $key => $val) :

if($days >= $key) {


$discount = $val;
}
endforeach;

$costForRental = ($days * $price['ItemPrice']['price'] * $qty) * (1 - ($discount/100));


$rental['cost'] = $costForRental;
$rental['discount'] = $discount;
$rental['period'] = $days;
$rental['qty'] = $qty;
$rental['unit_price'] = $rental['cost'] / $rental['qty'];

return $rental;
//$this->_prd($costForRental);

function _checkArray($array) {

if(!is_numeric($array['StockBooking']['startDate']['year'])) return false;


if(!is_numeric($array['StockBooking']['startDate']['month'])) return false;
if(!is_numeric($array['StockBooking']['startDate']['day'])) return false;
if(!is_numeric($array['StockBooking']['endDate']['year'])) return false;
if(!is_numeric($array['StockBooking']['endDate']['month'])) return false;
if(!is_numeric($array['StockBooking']['endDate']['day'])) return false;
if(!is_numeric($array['StockBooking']['itemId'])) return false;
if(!is_numeric($array['StockBooking']['qty'])) return false;
return true;

function _checkCart() {

if($this->Session->check('Mercury')) {
return true;
} elseif(!is_null($this->Cookie->read('Mercury'))) {
$this->Session->write('Mercury', unserialize($this->Cookie->read('Mercury')));
return true;
} else {
return false;
}
}

function _makeCart() {

$cart['id'] = String::uuid();
if($this->Session->check('Auth.User.id')) {
$cart['user_id'] = $this->Session->read('Auth.User.id');
} else {
$cart['user_id'] = 'NOT LOGGED IN';
}
$cart['date_created'] = date('Y-m-d');
$cart['value_goods'] = 0;
$cart['value_deposits'] = 0;
$this->Session->write('Mercury.Cart', $cart);
$this->Cookie->write('Mercury.Cart', $cart);
}

}
?>
<?php
class OrdersController extends AppController {

var $name = 'Orders';

function beforeFilter() {
parent::beforeFilter();
}

function afterFilter() {
parent::afterFilter();
}
}
?>
<?php
class SettingsController extends AppController {

var $name = 'Settings';

function beforeFilter() {
parent::beforeFilter();
}

function index() {
//Configure::write('Minilodgers.min_rental_days', '3');

$settings = Configure::read('Minilodgers');
//$this->_prd($settings);
$this->set('settings', $settings);
}

function admin_add() {
if(!empty($this->data)) {
Configure::write('Minilodgers.'.$this->data['Setting']['requester'].'.'.$this->data['Setting']
['key'], $this->data['Setting']['val']);
//$this->_prd(Configure::read('Minilodgers'));
//$this->redirect(array('controller' => 'settings', 'action' => 'index'));;
}
$this->redirect($this->referer());
}

function admin_shipping() {
//$minilodgers = Configure::read('Routing');
//$this->_prd($minilodgers);
$settings['Shipping'] = Configure::read('Minilodgers.Shipping');
$request = explode('_', $this->params['action'], 2);
$requester = $request['1'];
$this->set(compact('settings', 'requester'));
$this->render('admin_settings');
}

function afterFilter() {
parent::afterFilter();
}
}
?>
<?php
class ShippingController extends AppController {

var $name = 'Shipping';

var $uses = array('ShippingPostcode', 'ShippingPriceModel');

function beforeFilter() {
parent::beforeFilter();
}
function admin_index() {
$this->set('shipMode', $this->ShippingPriceModel->find('all'));
}

function admin_editModel($id = null) {


if(!empty($this->data)) {
$this->ShippingPriceModel->id = $this->data['ShippingPriceModel']['id'];
if($this->ShippingPriceModel->save($this->data)) {
$this->Session->setFlash('Shipping Option:.'.$this->data['ShippingPriceModel']['name'].'
has been updated', 'flash_success');
$this->redirect(array('admin' => true, 'controller' => 'shipping', 'action' => 'index'));
}
}
if($id) {
$model = $this->ShippingPriceModel->findById($id);
$this->data = $model;
$this->set('model', $model);
} else {
$this->redirect(array('admin' => true, 'controller' => 'shipping'));
}
}

function admin_addModel($id = null) {


if(!empty($this->data)) {
$this->ShippingPriceModel->create();
if($this->ShippingPriceModel->save($this->data)) {
$this->Session->setFlash('Shipping Option:.'.$this->data['ShippingPriceModel']['name'].'
has been created', 'flash_success');
$this->redirect(array('admin' => true, 'controller' => 'shipping', 'action' => 'index'));
}
}
}

function admin_switchModel($id = null, $changeto = null) {

if($id && is_numeric($changeto)) {


$this->data = $this->ShippingPriceModel->read(null, $id);
$this->data['ShippingPriceModel']['active'] = $changeto;
$this->ShippingPriceModel->id = $id;
if($this->ShippingPriceModel->save($this->data)) {
$this->Session->setFlash('The shipping option has been updated', 'flash_success');
$this->redirect($this->referer());
}
}
}

function afterFilter() {
parent::afterFilter();
}
}
?>
<?php
class SiteController extends AppController {

var $name = 'Site';

var $uses = array('Department', 'Site');

/*function display($slug = null) {

$departments = $this->Department->find('all');
$this->set('departments', $departments);

if(!$slug) {
$this->render('home');
} else {
$this->render($slug);
}
}*/

function display($slug = null) {


if($slug) {
$this->set('departments', $this->Department->find('all'));
$this->set('content', $this->Site->findBySlug($slug));
}
}

function admin_display($id = null) {


$this->set('page', $this->Site->findById($id));
}

function admin_index() {
$this->set('pages', $this->Site->find('all'));
}

function admin_add() {
if(!empty($this->data)) {
$this->Site->create();
if($this->Site->save($this->data)) {
$this->Session->setFlash('New page added to site', 'flash_success');
$this->redirect(array('admin' => true, 'controller' => 'site', 'action' => 'index'), true);
}
}
}

function admin_edit($id = null) {

if(!empty($this->data)) {
if(!empty($this->data)) {
$this->Site->id = $this->data['Site']['id'];
$this->Site->save($this->data);
}
}
$this->data = $this->Site->findById($id);
$this->set('content', $this->data);
}

function admin_delete($slug = null) {

}
}
?>
<?php
class StockBookingsController extends AppController {

var $name = 'StockBookings';

//var $scaffold;

function add() {

if(!empty($this->data)){
// get the dates array for the requested booking.
$dates = $this->StockBooking->calculateDates($this->data['StockBooking']);

//check the dates to see how they compare.


//step 1 get active stocks of the right type
$conditions = array(
'conditions' => array(
'Stock.active' => '1',
'Stock.item_id' => $this->data['StockBooking']['itemId'],
),
);

$activeStock = $this->StockBooking->Stock->find('all', $conditions);


$qty = $this->data['StockBooking']['qty'];
if(is_array($stockUnit = $this->StockBooking->checkDates($activeStock, $dates, $qty))) {
//$this->_prd($stockUnit);
echo "Yes! We have units available!";
}
else
{
echo "Sorry, we only have ".$stockUnit." units available!";
}

} else {

$stock = $this->StockBooking->Stock->find();
$this->set('stock', $stock);
}

}
}
?>
<?php
class StocksController extends AppController {

var $name = 'Stocks';

var $scaffold;

function stockCheck($itemId = null) {

if(!isset($itemId)) {

echo "Crap!";

} else {

$activeStock = $this->Stock->stockCheck($itemId);
$inactiveStock = $this->Stock->stockFindInactive($itemId);
$this->_prd($activeStock);
$item_type_id = $this->Stock->Item->findById($itemId);
$item_type = $this->Stock->Item->Category->findById($item_type_id['Item']
['category_id']);

$this->set(compact('activeStock', 'inactiveStock', 'item_type'));


}
}
}
?>
<?php
class UserAddressesController extends AppController {

var $name = 'UserAddresses';

var $paginate = array(


'limit' => 25,
'contain' => array('User')
);

function beforeFilter() {
parent::beforeFilter();
}

function admin_index() {
$this->set('addresses', $this->Paginate());
}

function admin_viewUser($id = null) {


if($id) {
$this->set('addresses', $this->UserAddress->findAllByUserId($id));
} else {
$this->redirect(array('action' => 'index'));
}
}

function admin_display($id = null) {


if($id) {
$this->set('address', $this->UserAddress->findById($id));
} else {
$this->redirect(array('action' => 'index'));
}
}

function afterFilter() {
parent::afterFilter();
}
}
?>

Anda mungkin juga menyukai