<?php
include_once"../config.php";
session_start();
$pid = $_POST['pid'];
$q = mysqli_query($con, "select value from emirate where id = '$pid' ");
$r = mysqli_fetch_object($q);
$uaevalue = $r->value;
$per = $_POST['per'];
$value = ($uaevalue*$per) / 100;
$name = $_POST['name'];
$status = $_POST['status'];
$id = isset($_POST['id'])?$_POST['id']:null;

$submit = isset($_POST['submit'])?$_POST['submit']:null;
$update = isset($_POST['update'])?$_POST['update']:null;
$delete = isset($_GET['delete'])?$_GET['delete']:null;


/***** Cross check pecent ***/
$cond = null;
if($id){$cond = " and id !=  $id ";}
$qc = mysqli_query($con, "select percent from area where pid = '$pid' and status = 1  $cond");

$cou = 0;
while($rc = mysqli_fetch_object($qc)){
	$cou += $rc->percent;
}
$cou =  $cou + $per;

if($cou > 100){ $_SESSION['try']=6;
header("location:../area.php?try=6");exit;}

/***** End Cross Check ***/

if($submit){
	$check = mysqli_query($con,"select * from area where name = '$name' and pid = '$pid'");
	if($check->num_rows == 0){
	mysqli_query($con, "INSERT INTO area set name= '$name', percent= '$per', value = '$value', status = '$status', pid = '$pid'  ");
    $_SESSION['try']=1;
	header("location:../area.php?try=1");
   }else{
		$_SESSION['try']=5;
   header("location:../area.php?try=5");
	}
}else if($update && $id){  echo 'zafar';
	mysqli_query($con, "update area set name= '$name', percent= '$per', value = '$value', status = '$status', pid = '$pid' where id =  $id ");
  $_SESSION['try']=2;
  header("location:../area.php?try=2");

}elseif($delete){
	mysqli_query($con, "delete from area where id =  $delete ");
   $_SESSION['try']=3;
   header("location:../area.php?try=3");
}