<?php

require 'db.php';

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
if(isset($postdata) && !empty($postdata))
{
$val = mysqli_real_escape_string($con, trim($request->value));
if($val != null)
{
    $s_sql = "SELECT * FROM subcategory where id = '$val'";
    $s_query = mysqli_query($con,$s_sql);
    if($rows = $s_query->fetch_assoc())
    {
        $status = $rows['catstatus'];
        $cat_val = $rows['cat_id'];
    }
    if($status != null)
    {
        $c_sql = "SELECT catstatus FROM category where id = '$cat_val'";
        $c_query = mysqli_query($con,$c_sql);
        if($row = $c_query->fetch_assoc())
        {
           $cat_status = $row['catstatus'];
        }
        if($cat_status == 1)
        {
            if($status==0)
            {
                $sc_sql = "UPDATE subcategory set catstatus = '1' where id='$val'";
                $sc_result = mysqli_query($con,$sc_sql);
                $p_sql = "UPDATE product set pstatus = '1' where sid='$val'";
                $p_result = mysqli_query($con,$p_sql);
                if($p_result)
                {
                    $rows = array('status'=>true,'message' => 'Sub-Category Status Changed');
                    echo json_encode($rows);
                    
                }
                else
                {
                    if($sc_result)
                    {
                        $rows = array('status'=>true,'message' => 'Sub-Category Status Changed');
                        echo json_encode($rows);
                    }  
                }
            }
            else if($status==1)
            {
                $sc_sql = "UPDATE subcategory set catstatus = '0' where id='$val'";
                $sc_result = mysqli_query($con,$sc_sql);
                $p_sql = "UPDATE product set pstatus = '0' where sid='$val'";
                $p_result = mysqli_query($con,$p_sql);
                if($p_result)
                {
                    $rows = array('status'=>true,'message' => 'Update Successfully');
                    echo json_encode($rows);
                    
                }
                else
                {
                    if($sc_result)
                    {
                        $rows = array('status'=>true,'message' => 'Update Successfully');
                        echo json_encode($rows);
                    }  
                }
            }
        }
        else
        {
            $sc_sql = "UPDATE subcategory set catstatus = '0' where id='$val'";
            $sc_result = mysqli_query($con,$sc_sql);
            $p_sql = "UPDATE product set pstatus = '0' where sid='$val'";
            $p_result = mysqli_query($con,$p_sql);
            $rows = array('status'=>false,'message' => 'Category is Off');
            echo json_encode($rows);
        }
    }
}
else
{
    $rows = array('status'=>false,'message' => 'Something Error');
    echo json_encode($rows);  
}
}

?>