<?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 $
***************************************************/
if (!defined('IN_COPPERMINE')) die('Not in Coppermine...');

$photoshop_home = dirname(__FILE__);
require_once($photoshop_home.'/include/functions.inc.php');

// Init
 $thisplugin->add_action('page_start','photoshop_start');

// Add plugin_install action
 $thisplugin->add_action('plugin_install','photoshop_install');

// Add plugin_uninstall action
 $thisplugin->add_action('plugin_uninstall','photoshop_uninstall');

// Add plugin_cleanup action
 $thisplugin->add_action('plugin_cleanup','photoshop_cleanup');

// Add plugin_configure action
 $thisplugin->add_action('plugin_configure','photoshop_configure');

// User menus
 $thisplugin->add_filter('template_html','photoshop_user_menu');

// Some filters
$thisplugin->add_filter('file_data','photoshop_add_item');


//functions
function photoshop_configure($stop=true)
{
    global $errors, $CONFIG;
    require ('include/sql_parse.php');

    $db_update = 'plugins/photo_shop/sql/basic.sql';
    $sql_query = fread(fopen($db_update, 'r'), filesize($db_update));
    // Update table prefix
    $sql_query = preg_replace('/CPG_/', $CONFIG['TABLE_PREFIX'], $sql_query);

    $sql_query = remove_remarks($sql_query);
    $sql_query = split_sql_file($sql_query, ';');

    ?>
        <h2>Performing Database Updates<h2>
        <table class="maintable">

    <?php

    foreach($sql_query as $q) {
        echo "<tr><td class='debug_text' style='color: black;'>
		{$q}
		</td>";
        if (mysql_query($q)) {
            echo "<td class='debug_text' style='color: green;'>OK</td></tr>";
        } else {
            echo "<td class='debug_text' style='color: black;'>Already Done</td></tr>";
        }
    }

    echo "</table>";
    
    if ($stop) {
        echo <<< EOT

        <form action="{$_SERVER['REQUEST_URI']}" method="post">
            <input type="submit" value="Go!" name="submit" />
        </form>
EOT;
    }

}

function photoshop_install(){
    // Install
    if ($_REQUEST['submit']=='Go!') {
        return true;
    } else {
        return 1;
    }
}

function photoshop_uninstall(){
        global $CONFIG;

        if (!isset($_POST['drop'])) return 1;

        if ($_POST['drop']) {
                cpg_db_query("DROP TABLE IF EXISTS {$CONFIG['TABLE_SHOP']}");
                cpg_db_query("DROP TABLE IF EXISTS {$CONFIG['TABLE_SHOP_CONFIG']}");
           }

        return true;
}

// Ask if we want to drop the table
function photoshop_cleanup($action) {

	global $lang_photoshop;

    if ($action===1) {
        echo <<< EOT
    <form action="{$_SERVER['REQUEST_URI']}" method="post">
        <p>
            {$lang_photoshop['uninstall']}
        </p>
        <div style="margin:25;">
        <table border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td><input type="radio" name="drop" value="1" /></td>
                <td>Yes</td>
            </tr>
            <tr>
                <td><input type="radio" name="drop" checked="checked" value="0" /></td>
                <td>No</td>
            </tr>
        </table>
        </div>
        <span>
           <input type="submit" name="submit" value="Submit" /> &nbsp;&nbsp;&nbsp;
            <input type="button" name="cancel" onClick="window.location='pluginmgr.php';" value="Cancel" />
        </span>
    </form>
EOT;
    }
}

function photoshop_add_admin_button($href,$title,$target,$link)
{
  global $template_gallery_admin_menu;

  $new_template=$template_gallery_admin_menu;
  $button=template_extract_block($new_template,'documentation');
  $params = array(
      '{DOCUMENTATION_HREF}' => $href,
      '{DOCUMENTATION_TITLE}' => $title,
      'target="cpg_documentation"' => $target,
      '{DOCUMENTATION_LNK}' => $link,
   );
   $new_button="<!-- BEGIN $link -->".template_eval($button,$params)."<!-- END $link -->\n";
   template_extract_block($template_gallery_admin_menu,'documentation',"<!-- BEGIN documentation -->" . $button . "<!-- END documentation -->\n" . $new_button);
}

function photoshop_start()
{
  global $CONFIG, $SHOP_CONFIG, $lang_photoshop, $lang_photoshop_config, $lang_photoshop;
  require 'plugins/photo_shop/include/init.inc.php';

  //add admin button
  photoshop_add_admin_button('index.php?file=photo_shop/photo_shop_admin',$lang_photoshop['admin_title'],'',$lang_photoshop['admin_title']);
}


function photoshop_user_menu(&$html){
    global $template_sys_menu_spacer, $lang_photoshop;
    $html = str_replace('{SUB_MENU}','{SUB_MENU} <br /> {CART_MENU}',$html);
    $cart_menu = "<a style=\"padding:2px;\" class=\"admin_menu\" href=\"index.php?file=photo_shop/photo_shop_cart\">".photoshop_count()." {$lang_photoshop['in_cart']}</a> ".$template_sys_menu_spacer." <a href=\"index.php?file=photo_shop/photo_shop_checkout\" style=\"padding:2px;\" class=\"admin_menu\">{$lang_photoshop['checkout']}</a>";
    $html = str_replace('{CART_MENU}',$cart_menu,$html);

    return $html;
}

function photoshop_count() {
	global $SHOP_CONFIG;
	$cd_counter = array();
	foreach($_SESSION['photoshop']['cart'] as $key => $temp){//foreach
		$amount = (isset($_SESSION['photoshop']['cart'][$key]['amount'])) ? $_SESSION['photoshop']['cart'][$key]['amount'] : '';
		$item_id = (isset($_SESSION['photoshop']['cart'][$key]['id'])) ? $_SESSION['photoshop']['cart'][$key]['id'] : '';
		if($item_id == 'CD') {
			$cd_counter['cd']++;
		} else {
			$cd_counter['photo'] = $cd_counter['photo'] + $amount;
		}
	
	}//end foreach 
	return ($cd_counter['cd'] + $cd_counter['photo']);

} 

function deep_in_array($value, $value2, $array) {
   foreach($array as $key =>$item) {
       if((in_array($value, $item)) && ($_SESSION['photoshop']['cart'][$key]['id'] == $value2)) {
			 return $key;
			 }
       else if(deep_in_array($value, $value2, $item)) return true;
   }
   return false;
}


function photoshop_add_item($pic_data){
	global $CONFIG, $SHOP_CONFIG, $lang_photoshop;
  	
	$html = "";
	$added = "";
	$event = isset($_POST['event']) ? $_POST['event'] : null;
	switch ($event) {
    	case 'add_item':
			if(isset($_POST['pid']))
			$added = '<center><font color="red">'.$lang_photoshop['added']."!</font></center>";
			$duplicate=deep_in_array($_POST['pid'],$_POST['item_id'],$_SESSION['photoshop']['cart']);//search array if item is already in cart.. then ++ amount of that item
			if(is_numeric($duplicate)){ // only add 1 item if it's for the CD
				if ($_SESSION['photoshop']['cart'][$duplicate]['id'] != "CD"){
					++$_SESSION['photoshop']['cart'][$duplicate]['amount'];
				} else {
					//break;
				}
			} else {
			$_SESSION['photoshop']['cart'][] = array(
		        'pid' => $_POST['pid'],
		        'id' => $_POST['item_id'],
		        'amount' => '1',
		        );
			}
			$cookie_data = base64_encode(serialize($_SESSION['photoshop']['cart']));
			setcookie($CONFIG['cookie_name'] . '_cart', $cookie_data, time() + 86400 * 30, $CONFIG['cookie_path']);
	
		break;
	}	

//loop through the items and create forms
	
	$html .= "<select name=\"item_id\" class=\"listbox_lang\">";
	foreach($SHOP_CONFIG as $key => $value) {
		if ($value['type'] == 'photo') { //we 
			$html.="<option value=\"{$value['id']}\">{$value['name']} - {$lang_photoshop['USD']}{$value['price']}</option>";
		} elseif ($value['type'] == 'cd') {
		 	$cd = true;
		} else {
			$cd = false;
		}
	} 
	$html .= ($cd) ? "<option value=\"CD\">{$lang_photoshop['CD']}</option>" : '';
	$html .="</select>";

	
	$shop_data =  <<<EOT
	<table class="shop_table">
		<tr>
			<td>
			<form action="{$REFERER}" method="post">
			  	{$added}{$lang_photoshop['buy']} {$html}
				<input type="hidden" value="{$pic_data['pid']}" name="pid" />
				<input type="hidden" value="add_item" name="event" />
    			<input type="submit" value="{$lang_photoshop['send']}" class="comment_button" />
			</form>
			</td>
		</tr>
	</table>

EOT;
	$pic_data['html'] = $shop_data.$pic_data['html'];
	$referer = ($_SERVER['PHP_SELF'] . (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] ? '?' . $_SERVER['QUERY_STRING'] : ''));
	if ($added) {
		//this is not nice.. but the menu updates before the content. So if you add an item, the basket count can't match
		// -> we have to refresh the page twice... can be removed but than the counter is wrong till the user manually reloads
	  	photoshop_refresh($referer);
		echo $added; // redundant ... while refreshing display 'item added'
		exit;
	}
	
	return $pic_data;
}

?>