<?php
require_once $_SERVER['DOCUMENT_ROOT'].
'/includes/access.inc.php';
if(!userIsLoggedIn()){
	include '../login.html.php';
	exit();
}

if(!userHasRole('Site Administrator')){
	$error='Only Site Administrators may access this page.';
	include '../accessdenied.html.php';
	exit();
}

if(isset($_GET['add'])){
	$pageTitle='دسته بندی جدید';
	$action='addform';
	$name='';
	$id='';
	$button='اضافه کردن دسته بندی';
	
	include 'form.html.php';
	exit();
}

if(isset($_GET['addform'])){
	include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
	try{
		$sql='insert into category set 
		name=:name';
		$s=$pdo->prepare($sql);
		$s->bindValue(':name',$_POST['name']);
		$s->execute();
	}
	catch(PDOException $e){
		$error='Error adding submitted category.';
		include 'error.html.php';
		exit();
	}
	header('location:.');
	exit();
}

if(isset($_POST['action']) and 
$_POST['action']=='Edit'){
	include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
	
	try{
		$sql='select id,name from category where id=:id';
		$s=$pdo->prepare($sql);
		$s->bindValue(':id',$_POST['id']);
		$s->execute();
	}
	catch(PDOException $e){
		$error='Error fetching category details.';
		include 'error.html.php';
		exit();
	}
	
	$row=$s->fetch();
	$pageTitle='ویرایش دسته بندی';
	$action='editform';
	$name=$row['name'];
	$id=$row['id'];
	$button='ویرایش دسته بندی';
	
	include 'form.html.php';
	exit();
}

if(isset($_GET['editform'])){
	include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
	
	try{
		$sql='update category set 
		name=:name
		where id=:id';
		$s=$pdo->prepare($sql);
		$s->bindValue(':id',$_POST['id']);
		$s->bindValue(':name',$_POST['name']);
		$s->execute();
	}
	catch(PDOException $e){
		$error='Error updating submitted category.';
		include 'error.html.php';
		exit();
	}
	header('location:.');
	exit();
}

if(isset($_POST['action']) and 
$_POST['action']=='Delete'){
	include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';
	
	try{
		$sql='delete from poemcategory where categoryid=:id';
		$s=$pdo->prepare($sql);
		$s->bindValue(':id',$_POST['id']);
		$s->execute();
	}
	catch(PDOException $e){
		$error='Error removing poems from category.';
		include 'error.html.php';
		exit();
	}
	
	try{
		$sql='delete from category where id=:id';
		$s=$pdo->prepare($sql);
		$s->bindValue(':id',$_POST['id']);
		$s->execute();
	}
	catch(PDOException $e){
		$error='Error deleting category.';
		include 'error.html.php';
		exit();
	}
	header('location:.');
	exit();
}

include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';

try{
	$result=$pdo->query('select id,name from category');
}
catch(PDOException $e){
	$error='Error fetching categories from database.';
	include 'error.html.php';
	exit();
}

foreach($result as $row){
	$categories[]=array(
	'id'=>$row['id'],
	'name'=>$row['name']);
}
include 'categories.html.php';








