<?php
/*
 * JohnCMS NEXT Mobile Content Management System (http://johncms.com)
 *
 * For copyright and license information, please see the LICENSE.md
 * Installing the system or redistributions of files must retain the above copyright notice.
 *
 * @link        http://johncms.com JohnCMS Project
 * @copyright   Copyright (C) JohnCMS Community
 * @license     GPL-3
 * Blogs By Aan Gabriel
 */

define('_IN_JOHNCMS', 1);

$id = isset($_REQUEST['id']) ? abs(intval($_REQUEST['id'])) : 0;
$act = isset($_GET['act']) ? trim($_GET['act']) : '';
//$mod = isset($_GET['mod']) ? trim($_GET['mod']) : '';
//$do = isset($_REQUEST['do']) ? trim($_REQUEST['do']) : false;


require('../system/bootstrap.php');
/** @var Psr\Container\ContainerInterface $container */
$container = App::getContainer();

/** @var PDO $db */
$db = $container->get(PDO::class);

/** @var Johncms\Api\UserInterface $systemUser */
$systemUser = $container->get(Johncms\Api\UserInterface::class);

/** @var Johncms\Api\ToolsInterface $tools */
$tools = $container->get(Johncms\Api\ToolsInterface::class);

/** @var Johncms\Api\ConfigInterface $config */
$config = $container->get(Johncms\Api\ConfigInterface::class);
/** @var Johncms\Api\BbcodeInterface $bbcode */
$bbcode = $container->get(Johncms\Api\BbcodeInterface::class);

 
require_once('../system/head.php');
if (!$systemUser->isValid()) {
   echo $tools->displayError('Login Before Write the Blogs!');
   require('../system/end.php');
   exit;
}

		$total = $db->query("SELECT COUNT(*) FROM `blogs_cat`")->fetchColumn();
		if($total) {
			if (isset ($_POST['submit'])) {
				$time = time();
				$timer = time();
				$date['day'] = date('d', $time);
				$date['year'] = date('o', $time);
				$date['month'] = date('m', $time);
				$date['i'] = date('i', $time);
				$date['h'] = date('h', $time);
				
				$name = isset ($_POST['name']) ? trim($_POST['name']) : '';
				$text = isset ($_POST['text']) ? trim($_POST['text']) : '';
				$cat = isset($_POST['cat']) ? abs(intval($_POST['cat'])) : 0;
				$day = isset($_POST['day']) && $_POST['day'] >= 1 && $_POST['day'] <= 31 ? abs(intval($_POST['day'])) : 0;
				$month = isset($_POST['month']) && $_POST['month'] >= 1 && $_POST['month'] <= 12 ? abs(intval($_POST['month'])) : 0;
				$year = isset($_POST['year']) && $_POST['year'] >= $date['year'] && $_POST['year'] <= ($date['year'] + 1) ? abs(intval($_POST['year'])) : 0;
				
				$hour = isset($_POST['hour']) && $_POST['hour'] >= 0 && $_POST['hour'] <= 24 ? abs(intval($_POST['hour'])) : 0;
				$minutes = isset($_POST['minutes']) && $_POST['minutes'] >= 0 && $_POST['minutes'] <= 60 ? abs(intval($_POST['minutes'])) : 0;
				
				$error = array();
		
				$error = array();
				
				if(empty($name))
					$error[] = 'Title Of Blogs Dont Leave Blank!';
				else if (mb_strlen($name) < 2 || mb_strlen($name) > 150)
					$error[] = 'Name blogs is erros short and Long of title name Blogs!';
				if(empty($text))
					$error[] =  'Blogs Dont Blank!';
				else if (mb_strlen($text) < 2 || mb_strlen($text) > 500000000)
					$error[] = 'Blogs text error min.2 max 500000000!';
				if(!$cat)
					$error[] =  'Please select the category!';
					
				if(empty($day) || empty($month) || empty($year)) {
					$timer = 0;
				} else {
					$time = strtotime("$day.$month.$year.$hour.$minutes");
            }
				/*
				if(!empty($timer) && $time < time())
					$error[] = 'Не верная дата!';
				*/
				if(!$error) {
					$data = $db->query("SELECT * FROM `blogs_cat` WHERE `id`='$cat';");
					if(!$data->rowCount())
						$error[] =  'Category not found!';
				}
				
				if(empty($error)) {
					$q = $db->query("SELECT * FROM `blogs` WHERE `name`='$name' LIMIT 1");
					if ($q->rowCount()) {
						$error[] = 'Blogs already exists!';
					}
				}
				
				if(empty($error)) {
             $db->prepare('
                 INSERT INTO `blogs` SET
                 `refid` = ?,
                 `name` = ?,
                 `text` = ?,
                 `user_id` = ?,
                 `time` = ?
             ')->execute([
                 $cat,        
                 $name,
                 $text,
                 $systemUser->id,
                 $time,
             ]);
			
					$img_id = $db->lastInsertId(); 					
					$handles = new upload($_FILES['imagefile']);
					if ($handles->uploaded) {
						// Обрабатываем фото
						$handles->file_new_name_body = 'news_' . $img_id;
						$handles->allowed = array('image/jpeg', 'image/jpg', 'image/gif', 'image/png');
						$handles->file_max_size = 1024 * $config['flsz'];
						$handles->file_overwrite = true;
						$handles->image_resize = true;
						$handles->image_x = 100;
						$handles->image_ratio_y = true;
						$handles->image_convert = 'jpg';
						$handles->process('../blogs/icon/');
						if($handles->processed) {
							@chmod('../blogs/icon/news_' . $img_id . '.jpg', 0666);
						}
                					
						$handles->file_new_name_body = 'small_news_' . $img_id;
						$handles->image_x = 32;
						$handles->image_y = 32;
						$handles->image_convert = 'jpg';
						$handles->process('../blogs/icon/');
						if($handles->processed) {
							@chmod('../blogs/icon/small_news_' . $img_id . '.jpg', 0666);
						}
						
					}
					$handles->clean();

					Header('Location: view.php?id='.$img_id);
					
				} else {
					echo $tools->displayError($error, '<a href="write.php">Try again!</a>');
				}
				
			} else {
				echo '<form action="write.php" method="post" enctype="multipart/form-data" name="form">
				<div class="gmenu"><p>
				<b>Blogs Title:</b><br />
				<input type="text" name="name" /><br />
				<small>Min. 2, max. 150 karakter</small><br />
				<b>Blogs text:</b><br />';
            echo $bbcode->buttons('form', 'text');
            echo '<textarea rows="' . $systemUser->getConfig()->fieldHeight . '" name="text"></textarea>
				<small>Min. 2, max. 5000 character</small><br />
				<b>Select Category:</b><br />
				<select name="cat">';
				$req = $db->query("SELECT * FROM `blogs_cat` ORDER BY `realid` ASC");
				while (($row = $req->fetch()) !== false) {
					echo '<option value="' . $row['id'] . '">' . htmlentities($row['name'], ENT_QUOTES, 'UTF-8') . '</option>';
				}

				echo '</select><br /><b>Date (empty for current date):</b><br />
				<table><tr>
				<td><span style="text-decoration: underline;">Date</span><br />
				<input type="text" value="" size="2" maxlength="2" name="day" />.</td>
				<td><span style="text-decoration: underline;">Mounth</span><br />
				<input type="text" value="" size="2" maxlength="2" name="month" />.</td>
				<td><span style="text-decoration: underline;">Year</span><br />
				<input type="text" value="" size="4" maxlength="4" name="year" />-</td>
				<td><span style="text-decoration: underline;">Hour</span><br />
				<input type="text" value="" size="2" maxlength="2" name="hour" />:</td>
				<td><span style="text-decoration: underline;">Minute</span><br />
				<input type="text" value="" size="2" maxlength="2" name="minutes" /></td>
				</tr></table>
				<small>Date on system ' . date('d.m.o / H:i', time() + $sdvigclock * 3600) . '<br />
				 Date content to display blog for a specified time</small><br />
				<b>Image blogs:</b><br />
				<input type="file" name="imagefile"/><br />
				<small>Format allowed: GIF, JPEG, JPG, PNG max.data 1000 kb<br />
				</small>
				<input type="hidden" name="MAX_FILE_SIZE" value="' . (1024 * $config['flsz']) . '" />
				</p><p><input type="submit" value="Add" name="submit" />
				</p></div></form>';
				
			}
		} else {
			echo '<div class="rmenu">Category Empty!</div>';
			
		}
		echo '<div class="phdr"><a href="index.php">Back to Blogs</a></div>';
	
		
require_once('../system/end.php');
?>