<?php
include("../../include/db.php");

/**************************** Check Item for ADD*****************************************/
function check_item($user_type)
{
$Isql=mysql_query("select * from user_type where user_type='$user_type' and delete_status!='1'");
$rscount=mysql_num_rows($Isql);
return $rscount;
}

/***************************** Check Item for Edit****************************************/
function check_user_type_edit($user_type)
{
 $sql_query="select * from user_type where user_type='$user_type' and delete_status!='1'";
 $rs=mysql_query($sql_query);
 $rscount1=mysql_num_rows($rs);
 if($rscount1!=0)
 {
 while($rsdata=mysql_fetch_object($rs))
 {
 $user_type_edit=$rsdata->user_type_id;
 } 
	return $user_type_edit;
 }
 }
 
/********************************** ADD ***************************************/
if($_POST['action']=='ADD')
{
$user_type=ucfirst($_POST['user_type']);
$active_status=$_POST['active_status'];
$create_date=date('Y-m-d');
$acadamic_yr=explode("-",$create_date);
$acdmc_yr_res=$acadamic_yr[0];
$check_item=check_item($_POST['user_type']);
if($check_item==0)
{
$Insql=mysql_query("insert into user_type(user_type,status,acad_yr,cr_date)values('$user_type','$active_status','$acdmc_yr_res','$create_date')");
echo "Successfully Added";
}
else
{
echo "Already Exists";
}
}
/*********************************** UPDATE QUERY *********************************************/
if($_POST['action']=='EDIT')
{
$edit_id=ucfirst($_POST['edit_id']);
$user_type=$_POST['user_type'];
$active_status=$_POST['active_status'];
$create_date=date('Y-m-d');
$acadamic_yr=explode("-",$create_date);
$acdmc_yr_res=$acadamic_yr[0];
$check_items=check_user_type_edit($user_type);
$check_item_count=check_item($user_type);
if(($check_items==$_POST['edit_id'])||($check_items==''))
{
$Insql=mysql_query("update user_type SET user_type='$user_type',status='$active_status',acad_yr='$acdmc_yr_res',cr_date='$create_date' where user_type_id='$_POST[edit_id]'");
echo "Updated Successfully!!";
}
else
{
echo "Already Exists";
}
}
/**********************************************************************************************/
if($_POST['action']== 'del_user_type')
{
include("../include/db_new.php");
if (!$DB) {
    die("❌ Failed to select database: " . mysql_error());
}

// Get and sanitize ID
$id = intval($_POST['id']);

// Perform soft delete
$deleteQuery = "UPDATE user_type SET delete_status='1' WHERE user_type_id='$id'";
$result = mysql_query($deleteQuery, $ConDB);

if (!$result) {
    die("❌ Query execution error: " . mysql_error());
}

if (mysql_affected_rows() > 0) {
    echo "<script>alert('Deleted Successfully');</script>";
} else {
    echo "<script>alert('No rows updated. ID may not exist.');</script>";
}

// Include the updated list
include("user_type_list.php");
 //include("user_type_list.php");
}
?>
