<?php
if ( ! defined( 'DATALIFEENGINE' ) ) {
    die( "Hacking attempt!" );
}


include_once  ROOT_DIR . '/language/' . $config['langs'] . '/table.lng';
@include_once  SYSTEM_DIR . '/data/tableconfig.php';

// ********************************************************************************
// Do add orders
// ********************************************************************************
if( $_REQUEST['action'] == "view" ) {
	$id = intval( $_GET['id'] );
	$db->query( "SELECT * FROM " . PREFIX . "_table where id= '$id'" );
	$row = $db->get_row();

	if( $db->num_rows() < 1 ) {
		msgbox( $lang['all_err_1'],  "Заказа под таким номером не найдено" );
	} else {
            if ( $row['runame'] ){ $title = stripslashes($row['runame']); }
            elseif ( $row['enname'] ){ $title = stripslashes($row['enname']); }
            $metatags['title'] = 'Стол заказов' . ' &raquo; ' . $title . ' &raquo; ' . $config['home_title'];

            $inetlink = explode("\n", stripslashes($row['answer']));
            $inetlink_1 = '<a href="';
            $inetlink_2 = '" target="_blank"><b>Перейти в новость</b></a>';
            $inetlink_s = $inetlink_1 . join("$inetlink_2 | $inetlink_1", $inetlink) . $inetlink_2;

			$status = intval($row['status']);
            switch ($status) {
                case "0":
                    $status = '<font color=\'#FF8000\'>' . $lang_table['edit_status_0'] . '</font>';
                    $answer = '';
                    break;
                case "1":
                    $status = '<font color=\'#0000FF\'>' . $lang_table['edit_status_1'] . '</font>';
                    $answer = '';
                    break;
                case "2":
                    $status = '<font color=\'#FF0000\'>' . $lang_table['edit_status_2'] . '</font>';
					if (empty($row['answer'])) {$answer = $lang_table['cause1'];
					} else {$answer = $lang_table['cause0'] . stripslashes($row['answer']); }
                    break;
                case "3":
                    $status = '<font color=\'#008000\'>' . $lang_table['edit_status_3'] . '</font>';
                    $answer = "<br /><b>Новость с выполненным заказом: </b>" . $inetlink_s;
                    break;
            }

			if ( $member_id['user_group'] == '1' OR $user_group[$member_id['user_group']]['admin_table'] OR $member_id['user_group'] == $table_config['grouplevel'] ) {
                $admin_url = '<a href="/' . $config['admin_path'] . '?mod=table&user_hash=' . $dle_login_hash . '&action=edit&id=' . intval($row['id']) . '" target="_blank">' . $lang_table['edit'] . '</a>';
            }

		$tpl->load_template('tableview.tpl');
		$tpl->set( '{adminlink}', $admin_url );

		$row['date'] = /*strtotime*/($row['date']);
		if (date(Ymd, $row['date']) == 	date(Ymd, $_TIME)) {

			$tpl->set('{date}',  $lang['time_heute'].langdate(" в H:i", $row['date']));

		} elseif (date(Ymd, $row['date']) == date(Ymd, ($_TIME - 86400))) {

			$tpl->set('{date}',  $lang['time_gestern'].langdate(" в H:i", $row['date']));

		} else {

			$tpl->set('{date}',  langdate($table_config['timestamp_active'], $row['date']));

		}
        $tpl->set( '{id-orders}', $id );
        $tpl->set( '{autor}', "<a href=\"" . $config['http_home_url'] . "user/" . urlencode(  stripslashes($row['autor']) ) . "/\">" .$row['autor']. "</a>" );

		$tpl->set( '{runame}', stripslashes($row['runame']));
		$tpl->set( '{enname}', stripslashes($row['enname']));
		$tpl->set( '{category}', stripslashes($row['category']));
		$tpl->set( '{fileyear}', stripslashes($row['fileyear']));
		$tpl->set( '{status}', $status);
		$tpl->set( '{answer}', $answer);
        $tpl->set( '{editor}', "<a href=\"" . $config['http_home_url'] . "user/" . urlencode(  stripslashes($row['editor']) ) . "/\">" .$row['editor']. "</a>" );

		if( $row['editor'] ) {
			$tpl->set( '[editor]', "" );
			$tpl->set( '[/editor]', "" );
		} else {
			$tpl->set( '{editor}', "" );
			$tpl->set_block( "'\\[editor\\](.*?)\\[/editor\\]'si", "" );
		}

		$tpl->compile( 'content' );
		$tpl->clear();

    }
    }
elseif ( $_REQUEST['action'] == "doadd" ) {

	$metatags['title'] = $lang_table['description2'] . ' &raquo; ' . $config['home_title'];
	$timeweek = $_TIME - (intval($table_config['timeweek']) * 86400);

	$row_doadd = $db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_table WHERE autor = '" . $member_id['name'] . "' AND date >'$timeweek' AND status != '2' AND status != '3'");
	if ($row_doadd['count'] >= 1) { $is_doadd = false; }
	else { $is_doadd = true; }

    if (isset($_POST['send'])) {
		$stop = "";

		$user_n = $db->safesql(trim($member_id['name']));
		$runame = $db->safesql(strip_tags(trim($_POST['runame'])));
		$enname = $db->safesql(strip_tags(trim($_POST['enname'])));
		$category = $db->safesql(strip_tags(trim($_POST['category'])));
		$fileyear = $db->safesql(strip_tags(trim($_POST['fileyear'])));
		$link = $db->safesql(strip_tags(trim($_POST['link'])));

		if ( trim( $runame ) != "" or $runame ){ $name = $runame; }
        if ( trim( $enname ) != "" or $enname ){ $name = $enname; }
        if( !$name ){$stop .= $lang_table['err_name'];}

		if ( trim( $category ) == "" or ! $category ) {$stop .= $lang_table['orders_err_category'];}
		if ( trim( $fileyear ) == "" or ! $fileyear ) {$stop .= $lang_table['err_year'];}
		if (!is_numeric($fileyear)) {$stop .= $lang_table['err_year_type'];}
		if( strlen( $runame ) > 40 ) {$stop .= '<li>' . $lang_table['orders_err_name'] . '</li>';}
		if( strlen( $fileyear ) > 4 ) {$stop .= '<li>' . $lang_table['orders_err_year'] . '</li>';}
		if( strlen( $category ) > 20 ) {$stop .= '<li>' . $lang_table['orders_err_category'] . '</li>';}

		if (intval($table_config['auto_wrap'])) {
			$link = preg_split('((>)|(<))', $link, -1, PREG_SPLIT_DELIM_CAPTURE);
			$n = count($link);
                for ($i = 0; $i < $n; $i++) {
                    if ($link[$i] == "<") {
                        $i++;
                        continue;
                    }
                    $link[$i] = preg_replace("#([^\s\n\r]{" . intval($table_config['auto_wrap']) . "})#i", "\\1<br />", $link[$i]);
                }
                $link = join("", $link);
            }

		if ( $stop ) {
			msgbox($lang['all_err_1'], "<ul>" . $stop . "</ul><a href=\"javascript:history.go(-1)\">$lang[all_prev]</a>");
		} else {
			$db->query("INSERT INTO " . PREFIX . "_table SET date='$_TIME', autor='$user_n', runame='$runame', enname='$enname', fileyear='$fileyear', category='$category'");
            $cache->clear("toporders", $config['skin']);

			if ( $table_config['msgs_adm'] == "yes" ) {
				$step = 0;
				$result = $db->query("SELECT user_id, name, email FROM " . USERPREFIX . "_users WHERE user_group = '$table_config[grouplevel]'");

				$path = $config['http_home_url'];
				$subject = $lang_table['msgs_subject'];
				$user_from = $lang_table['msg_user_from'];
				$message .= $runame . " / " . $enname . " ({$fileyear})";

					$user_n =  "<a href=\"{$path}user/" . urlencode($user_n) . "/\"><strong>" . $user_n . "</strong></a>";

				$table_config['msgs_type0'] = stripslashes( html_entity_decode( $table_config['msgs_type0'] ) );
				$table_config['msgs_type0'] = str_replace( "{%username_from%}", $user_n, $table_config['msgs_type0'] );
				$table_config['msgs_type0'] = str_replace( "{%category%}", $category, $table_config['msgs_type0'] );
				$table_config['msgs_type0'] = str_replace( "{%text%}", $message, $table_config['msgs_type0'] );
				$table_config['msgs_type0'] = str_replace( "{%date%}", date("d.m.Y H:i:s", $_TIME), $table_config['msgs_type0'] );
				$table_config['msgs_type0'] = str_replace( "{%ip%}", $_SERVER['REMOTE_ADDR'], $table_config['msgs_type0'] );

				if ( $table_config['msgs_type'] == "0" ) {
					while ($row = $db->get_row($result)) {
						$db->query("INSERT INTO " . USERPREFIX . "_pm (subj, text, user, user_from, date, pm_read, folder) values ('$subject', '$table_config[msgs_type0]', '$row[user_id]', '$user_from', '$_TIME', 'no', 'inbox')");
						$db->query("UPDATE " . USERPREFIX . "_users set pm_all=pm_all+1, pm_unread=pm_unread+1  WHERE user_id='$row[user_id]'");
						$step++;
					}
				} else {
					//$recipient = $db->super_query( "SELECT email FROM " . USERPREFIX . "_users WHERE user_group = '$table_config[grouplevel]'" );
					include_once SYSTEM_DIR . '/classes/mail.class.php';
					$mail = new dle_mail( $config, true );
					$mail->from = $config['admin_mail'];
					
					while ($recipient = $db->get_row($result)) {
						$mail->send( $recipient['email'], $subject, $table_config['msgs_type0'] );
						$step++;
					}
				if( $mail->send_error ) msgbox( $lang['all_info'], $mail->smtp_msg );
				else die(header("Location: " . $_SERVER['PHP_SELF'] . '?do=table'));
				}
				$db->free($result);
			}
			$db->free();
			die(header("Location: " . $_SERVER['PHP_SELF'] . '?do=table')); // commment line to Test $mail->send_error
		}
	} else {
		if (!$is_logged) {
			msgbox($lang['all_err_1'], "$lang_table[not_logged]");
		} elseif ($is_doadd != true) {
			msgbox($lang['all_err_1'], "$lang_table[one_orders]");
		} else {
			$tpl->load_template('table.tpl');
			$tpl->set( '{description}', $lang_table['description2'] );
			$tpl->set_block( "'\\[doadd\\](.*?)\\[/doadd\\]'si", "" );
			$tpl->set( '[newadd]', "" );
			$tpl->set( '[/newadd]', "" );

			$category_s = explode(",", stripslashes($table_config['category']));
			$category = "<select size=7 name=\"category\">\r\n";
				foreach ( $category_s as $value => $description ) {
					$category .= "<option value=\"$description\"";
					if( $selected == $description ) {
						$category .= " selected ";
					}
					$category .= ">$description</option>\n";
				}
			$category .= "</select>";

			$tpl->set('{category}', $category);
            
			$tpl->copy_template = "<form  method=\"post\" name=\"frmMain\" action=\"\">\n" . $tpl->copy_template . "<input name=\"send\" type=\"hidden\" value=\"send\" /></form>";
			$tpl->compile('content');
			$tpl->clear();
		}
        }
} else {
    $status = @$db->safesql( trim($_GET['status']));
    $ordstat = 0;
    $ordpage = '';
    $ordtitle = 'Ожидающие';

    if($status=='accepted'){
        $ordstat = 1;
        $ordtitle = 'Принятые';
        $ordpage = 'accepted/';
    }elseif($status=='finished'){
        $ordstat = 3;
        $ordtitle = 'Выполнено';
        $ordpage = 'finished/';
    }elseif($status=='aborted'){
        $ordstat = 2;
        $ordtitle = 'Отклонено';
        $ordpage = 'aborted/';
    }

	$metatags['title'] = $lang_table['description'] . ' &raquo; ' . $ordtitle . ' &raquo; ' . $config['home_title'];

	$tpl->load_template( 'table.tpl' );
	$tpl->set( '{description}', $lang_table['description'] );
	$tpl->set( '[doadd]', "<a href=\"$PHP_SELF?do=table&amp;action=doadd\">" );
	$tpl->set( '[/doadd]', "</a>" );
	$tpl->set_block( "'\\[newadd\\](.*?)\\[/newadd\\]'si", "" );
	$tpl->compile('content');
	$tpl->clear();

    $limit = intval ( $table_config['orders_number'] );
    $sql_count = $db->super_query("SELECT COUNT(*) as count FROM " . PREFIX . "_table where status=$ordstat");
   	$count_all = $sql_count['count'];

    $page = intval( $_REQUEST['cstart'] );
    $total = intval( ( ( $count_all - 1 ) / $limit ) + 1 );
	if( $page <= 0 ) $page = 1;
	if( $page > $total ) $page = $total;
    $start = $page * $limit - $limit;
	$i = $start;

	$order_direction_by = ($table_config['orders_msort']) ? $table_config['orders_msort'] : "ASC";
	
	$sql_select = "SELECT * FROM " . PREFIX . "_table where status=$ordstat ORDER BY date $order_direction_by LIMIT " . $start . "," . $limit;

	$sql_result = $db->query($sql_select);
	
	while ($row = $db->get_row()) {
		$i++;
			$status = intval($row['status']);
            switch ($status) {
                case "0":
                    $status = '<font color=\'#FF8000\'>' . $lang_table['edit_status_0'] . '</font>';
                    break;
                case "1":
                    $status = '<font color=\'#0000FF\'>' . $lang_table['edit_status_1'] . '</font>';
                    break;					
                case "2":
                    $status = '<font color=\'#FF0000\'>' . $lang_table['edit_status_2'] . '</font>';
                    break;					
                case "3":
                    $status = '<font color=\'#008000\'>' . $lang_table['edit_status_3'] . '</font>';
                    break;
            }

			if ( $member_id['user_group'] == '1' OR $user_group[$member_id['user_group']]['admin_table'] OR $member_id['user_group'] == $table_config['grouplevel'] ) {
                $admin_url = '<a href="/' . $config['admin_path'] . '?mod=table&user_hash=' . $dle_login_hash . '&action=edit&id=' . intval($row['id']) . '" target="_blank">' . $lang_table['edit'] . '</a>';
            }

		$tpl->load_template('tableshow.tpl');
		$tpl->set( '{id-orders}', $i );
        $tpl->set( '{id-link}', intval($row['id']) );
		$tpl->set( '{adminlink}', $admin_url );

		$row['date'] = /*strtotime*/($row['date']);
		if (date(Ymd, $row['date']) == 	date(Ymd, $_TIME)) {$tpl->set('{date}',  $lang['time_heute'].langdate(" в H:i", $row['date']));
		} elseif (date(Ymd, $row['date']) == date(Ymd, ($_TIME - 86400))) {$tpl->set('{date}',  $lang['time_gestern'].langdate(" в H:i", $row['date']));
		} else {$tpl->set('{date}',  langdate($table_config['timestamp_active'], $row['date']));}

		$tpl->set( '{autor}', stripslashes($row['autor']));
		$tpl->set( '{category}', stripslashes($row['category']));
		$tpl->set( '{status}', $status);

		$tpl->set('{navigation}', "$navigation");
		$tpl->compile('content');
		$tpl->clear();
		}

	$db->free();

    $nav = "/orders/" . $ordpage . "page/{page}";
    CreateNavigation( $nav, $page, $total );
}
?>