<?php
/**************************************************
  CPG Photo Shop Plugin for Coppermine Photo Gallery
  *************************************************
  Copyright (c) 2006 Thomas Lange <stramm@gmx.net>
  *************************************************
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
  *************************************************
  Coppermine version: 1.4.5
  Photo Shop version: 1.0
  $Revision: 1.0 $
  $Author: stramm $
***************************************************/
define('PHOTOSHOP_ORDER_PHP', true); 

require('include/init.inc.php');
require('include/mailer.inc.php');
if (!file_exists("plugins/photo_shop/lang/{$CONFIG['lang']}.php"))
  $CONFIG['lang'] = 'english';
require "plugins/photo_shop/lang/{$CONFIG['lang']}.php";

if (!defined('IN_COPPERMINE')) die('Not in Coppermine...');
//cart empty??
$cd_counter = photoshop_count_items();
if (($cd_counter['cd']+$cd_counter['photo']) == 0 ) {
			pageheader($lang_photoshop['checkout']);
			starttable('100%', $lang_photoshop['checkout'], 1);
			msg_box('', $lang_photoshop['cart_empty'], $lang_continue, 'index.php');
			pagefooter();
			exit;
}
//if user isn't logged in redirect to shop register/ login page
if(!USER_ID) { 
    photoshop_refresh($_SERVER['PHP_SELF'].'?file=photo_shop/photo_shop_register');
	exit;
}
//start html output
pageheader($lang_photoshop['checkout']);
starttable('100%', $lang_photoshop['checkout'], 1);

//start all teh if else
$cd_price = item_price($cd_counter['cd']);
if ($cd_price[3] == false) { // more CD items than max defined -> warn and show link to cart
	echo '<tr><td><br>'.$cd_price[2].'<br>'.$lang_photoshop['goto_cart_cd'].'</td></tr>';
} elseif (($_POST['order'] == "confirmed") && (($cd_counter['cd']+$cd_counter['photo']) > 0 )) {
	//add to mysql, show confirmation and send email (user+admin)
	photoshop_prep_data(&$shop_array_cd, &$shop_array_photos);
	
	//order_id++
	$results = cpg_db_query("SELECT oid FROM {$CONFIG['TABLE_SHOP']} ORDER BY oid DESC LIMIT 1");
	$row = mysql_fetch_array($results);
	$order_id = ++$row['oid'];
	mysql_free_result($results);
	
	//merge photo und cd array
	$shop_array = array_merge($shop_array_photos, $shop_array_cd);
	
	if (photoshop_add_data($shop_array, $order_id)) { // adding data succeeded
		//now email the user
		if(photoshop_email_the_user($lang_photoshop_email_order, $lang_photoshop['email_subject_order'])){
			//when user got his email, then send to admin
			cpg_mail('admin', sprintf($lang_photoshop['email_subject_order_admin'], $CONFIG['gallery_name']), nl2br($lang_photoshop_email_admin));
			//now we just need to clear the cookie/ session and done
			setcookie($CONFIG['cookie_name'] . '_cart', '', time() + 86400 * 30, $CONFIG['cookie_path']);
			unset ($_SESSION['photoshop']['cart']);

			msg_box('', $lang_photoshop['email_sent'], $lang_continue, 'index.php');
		}
	
	pagefooter();
	exit; // we'Re done here	
	} else {
		//something went wrong
	}

} else {
	//show the cart contents and price, submit button
	echo "<form action='{$_SERVER['PHP_SELF']}?file=photo_shop/photo_shop_checkout' method='post'>";
	
	photoshop_prep_data(&$shop_array_cd, &$shop_array_photos);
	photoshop_create_table($shop_array_photos, "photo");
	photoshop_create_table($shop_array_cd, "cd");
	photoshop_format_price($cd_price, $cd_counter, '');
	
	echo <<<EOT
                <tr>
                        <td align="left" class="tablef" colspan="7">
                            <table border="0" cellspacing="0" cellpadding="0" width="100%">
                                <tr>
                                    <td width="100%" align="center">
                                        <input type="hidden" name="order" value="confirmed" />
                                        <input type="submit" class="button" name="apply" value="{$lang_photoshop['send_order']}" />
                                    </td>
                                </tr>
                            </table>
                        </td>
                </tr>
EOT;
}

endtable();
echo "</form>";
pagefooter();
ob_end_flush();

//functioons
function photoshop_prep_data($shop_array_cd, $shop_array_photos) {
	$shop_array_photos = array(); //temp array for easier use
	$shop_array_cd = array(); //temp array for easier use
	foreach ($_SESSION['photoshop']['cart'] as $key => $item_id) {
		if ($item_id['id'] == 'CD') {
			$shop_array_cd[] = $_SESSION['photoshop']['cart'][$key];
		} else {
			$shop_array_photos[] = $_SESSION['photoshop']['cart'][$key];
		}
	}
}

function photoshop_create_table($shop_array_photos, $type){
	global $SHOP_CONFIG, $CONFIG, $lang_photoshop, $cd_price;
	echo '<tr><td><table cellpadding="0" cellspacing="1" width="100%">';
	
	if ($type == photo) {
	echo <<<EOT
		<tr>
			<td class="tableh1" width="25%">Item ID</td>
			<td class="tableh1" width="25%">Type</td>
			<td class="tableh1" width="25%">Amount</td>
			<td class="tableh1" width="25%">Price total</td>
		</tr>
EOT;
	} else {
	echo <<<EOT
		<tr>
			<td class="tableh1" width="25%">Item ID</td>
			<td class="tableh1" width="25%">Type</td>
			<td class="tableh1" width="25%">&nbsp;</td>
			<td class="tableh1" width="25%">&nbsp;</td>
		</tr>
EOT;
	}
	foreach ($shop_array_photos as $key => $item_id) {
		$select_columns = 'filepath, filename, url_prefix, filesize, pwidth, pheight, ctime, title';
	
	    $result = cpg_db_query("SELECT $select_columns from {$CONFIG['TABLE_PICTURES']} WHERE pid='{$item_id['pid']}' LIMIT 1");
	    $row = mysql_fetch_array($result);
	
		$thumb_url= get_pic_url($row, 'thumb');
		
		//html resize thumb
		$new_size = 60;
	    $ratio = max($row['pwidth'], $row['pheight']) / $new_size;
	    $ratio = max($ratio, 1.0);
	    $destWidth = (int)($row['pwidth'] / $ratio);
	    $destHeight = (int)($row['pheight'] / $ratio);
	
		if ($item_id['id'] == 'CD') {
			echo <<<EOT
				<tr>
					<td>
					<a href="displayimage.php?pos=-{$item_id['pid']}"><img class="image" src="{$thumb_url}" width="{$destWidth}" height="{$destHeight}" alt="" /></a>
					</td>
					<td>{$item_id['id']}</td>
					<td>&nbsp;</td>
					<td>&nbsp;</td>
				</tr>
EOT;

		} else {
		$price = number_format($SHOP_CONFIG[$item_id['id']]['price']*$item_id['amount'],2);
			echo <<<EOT
				<tr>
					<td>
					<a href="displayimage.php?pos=-{$item_id['pid']}"><img class="image" src="{$thumb_url}" width="{$destWidth}" height="{$destHeight}" alt="" /></a>
					</td>
					<td>{$SHOP_CONFIG[$item_id['id']]['name']}</td>
					<td>{$item_id['amount']}</td>
					<td>{$lang_photoshop['USD']} {$price}</td>
				</tr>
EOT;
		}
	}
	echo "</td></tr></table>";
}

function photoshop_add_data($shop_data, $order_id){
	global $CONFIG, $SHOP_CONFIG, $cd_price, $cd_counter;
	
	$otime = time();
	$results2 = cpg_db_query ("INSERT INTO `{$CONFIG['TABLE_SHOP']}` (`oid`, `uid`, `cd`, `quantity`, `price`, `otime`) VALUES ('$order_id', '".USER_ID."', '1', '".($cd_counter['cd']+$cd_counter['photo'])."', '".(number_format(($cd_price[0]+$cd_price[1]),2))."', '$otime')");

	foreach ($shop_data as $key => $item_id) {
		$pid = $item_id['pid'];
		$amount = $item_id['amount'];
		if ($item_id['id']=="CD") {
			$size = "CD";
			$price = $cd_price[1];
		} else {
			$size = $SHOP_CONFIG[$item_id['id']]['name']; 
			$price = $SHOP_CONFIG[$item_id['id']]['price'];
		}
		
		
		$results = cpg_db_query ("INSERT INTO `{$CONFIG['TABLE_SHOP']}` (`oid`, `uid`, `pid`, `quantity`, `size`, `price`, `otime`) VALUES ('$order_id', '".USER_ID."', '$pid', '$amount', '$size', '$price', '$otime')");

	}
	return $results;
}

function photoshop_email_the_user($message, $subject)
{

	global $CONFIG, $lang_photoshop, $cd_price, $order_id;
	
	$user_info = photoshop_user_details(USER_ID);
	$template_vars = array(
	'{ORDER_ID}' => $order_id,
	'{SITE_NAME}' => $CONFIG['gallery_name'],
	'{PRICE}' => number_format(($cd_price[0]+$cd_price[1]),2),
	'{USER_NAME}' => (USER_NAME),
	'{ADMIN}' => $CONFIG['gallery_name'],
	'{LINK}' => $CONFIG['ecards_more_pic_target'],
	);
	$mail_body=nl2br(strtr($message, $template_vars));
	if(cpg_mail($user_info['user_email'], $subject, $mail_body, 'text/plain', $CONFIG['gallery_name'], $CONFIG['gallery_admin_email'] )) {
		return true;
	}	
	return false;
}

function photoshop_user_details($id){
	global $cpg_udb;
	$user_name = $cpg_udb->get_user_infos($id);
	return $user_name;
}

?>