Whole Script

download Whole Script

of 50

Transcript of Whole Script

  • 8/8/2019 Whole Script

    1/50

  • 8/8/2019 Whole Script

    2/50

    $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'tif(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'];

  • 8/8/2019 Whole Script

    3/50

    $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 tocheck 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'tif(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']);

  • 8/8/2019 Whole Script

    4/50

    } 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');

    }

    }

  • 8/8/2019 Whole Script

    5/50

    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 tocheck 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'tif(is_array($checkedStock = $this->StockBooking->checkDates($stockList, $dates, $qty)))

  • 8/8/2019 Whole Script

    6/50

    {

    //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']);

  • 8/8/2019 Whole Script

    7/50

    //} 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');

  • 8/8/2019 Whole Script

    8/50

    $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']

  • 8/8/2019 Whole Script

    9/50

    ['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);

    }}

  • 8/8/2019 Whole Script

    10/50

    function userLogin() {if($this->Session->check('Auth.User.id')) {

    $this->redirect(array('controller' => 'cart', 'action' => 'chooseAddresses'), true);}

    }

    function shippingInfo() {

    }

    //PRIVATE FUNCTIONSfunction _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

  • 8/8/2019 Whole Script

    11/50

    $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);

  • 8/8/2019 Whole Script

    12/50

    }

    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 thisreturn 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 toadapt the existing entry.

    return false;}

    endforeach;}

    return true;

    //$this->_testData($this->data) && !empty($this->data}

  • 8/8/2019 Whole Script

    13/50

    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();

  • 8/8/2019 Whole Script

    14/50

    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');}

    }}

    ?>

  • 8/8/2019 Whole Script

    15/50

    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());

  • 8/8/2019 Whole Script

    16/50

    }}

    }?>

  • 8/8/2019 Whole Script

    17/50

    if(!empty($_POST)){//...we have so add 'cmd' 'notify-validate' to a transaction variable$transaction = 'cmd=notify-validate';//and add everything paypal has sent to the transactionforeach ($_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';

    }//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 INVALIDfputs ($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->/_processTransaction($this->InstantPaymentNotification->id);

    }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.

  • 8/8/2019 Whole Script

    18/50

    }}?>

  • 8/8/2019 Whole Script

    19/50

    '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');

    }

  • 8/8/2019 Whole Script

    20/50

    $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());

    }}

    }

    ?>

  • 8/8/2019 Whole Script

    21/50

    function checkItem() {

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

    //using the dates input, firstly make them useful, then compare them to the cookie - updatecookie 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'tif(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);

  • 8/8/2019 Whole Script

    22/50

    $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.

  • 8/8/2019 Whole Script

    23/50

    //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'tif(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){

  • 8/8/2019 Whole Script

    24/50

    $days = $minDays;}

    $conditions1 = array(

    'conditions' => array('DiscountPeriod.days

  • 8/8/2019 Whole Script

    25/50

    $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')) {

  • 8/8/2019 Whole Script

    26/50

    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 thisreturn 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);

    }}

  • 8/8/2019 Whole Script

    27/50

    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;

  • 8/8/2019 Whole Script

    28/50

    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;}

    }

  • 8/8/2019 Whole Script

    29/50

    //$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);

    } */}

    ?>

  • 8/8/2019 Whole Script

    30/50

  • 8/8/2019 Whole Script

    31/50

    }

    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;

  • 8/8/2019 Whole Script

    32/50

    } 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'],

  • 8/8/2019 Whole Script

    33/50

    '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}

    }

  • 8/8/2019 Whole Script

    34/50

    }

    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());}

  • 8/8/2019 Whole Script

    35/50

    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,

  • 8/8/2019 Whole Script

    36/50

    ));$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;}

    }}

    ?>

  • 8/8/2019 Whole Script

    37/50

    $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'],

  • 8/8/2019 Whole Script

    38/50

    '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']) :

  • 8/8/2019 Whole Script

    39/50

    $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 {

  • 8/8/2019 Whole Script

    40/50

    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(

  • 8/8/2019 Whole Script

    41/50

    '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) {

  • 8/8/2019 Whole Script

    42/50

    $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', $endDay),

    ),array(

    'ItemPrice.start_date ' => date('Y-m-d', $endDay),

    ),

    array('ItemPriceDiscount.start_date

  • 8/8/2019 Whole Script

    43/50

    App::import('Model', 'Discount');$Discount = new Discount;$conditions3 = array('conditions' => array(

    'OR' => array(array(

    'Discount.start_date ' => date('Y-m-d', $endDay),),array(

    'Discount.start_date

  • 8/8/2019 Whole Script

    44/50

    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);

    }

    }?>

  • 8/8/2019 Whole Script

    45/50

  • 8/8/2019 Whole Script

    46/50

    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();

    }}

    ?>

  • 8/8/2019 Whole Script

    47/50

  • 8/8/2019 Whole Script

    48/50

    }}

    $this->data = $this->Site->findById($id);$this->set('content', $this->data);

    }

    function admin_delete($slug = null) {

    }}

    ?>

  • 8/8/2019 Whole Script

    49/50

    }?>

  • 8/8/2019 Whole Script

    50/50

    } 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();

    }

    }?>