<?php

require 'db.php';

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
if(isset($postdata) && !empty($postdata))
{
$mode = mysqli_real_escape_string($con, trim($request->mode));
$bannerid = mysqli_real_escape_string($con, trim($request->bannerid));
$bannerimg = mysqli_real_escape_string($con, trim($request->form_value->fileSource));

// db name = banner

if($mode == "add")
{
    if($bannerimg == null)
    {
        $rows = array('status'=>false,'message' => 'Fields Missing');
        echo json_encode($rows);
    }
    else
    {
        $folderPath = "banner/";
        $image_parts = explode(";base64,", $bannerimg);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);
        $file = $folderPath . uniqid() . '.png';
        file_put_contents($file, $image_base64);
        
        $sql = "INSERT INTO cat_banner(bimg) VALUES ('$file')";
        $result = mysqli_query($con,$sql);
        if($result)
        {
            $rows = array('status'=>true,'message' => 'Category Banner Added');
            echo json_encode($rows);
        }
    }
}

else if($mode == "edit")
{
    if($bannerid == null)
    {
        $rows = array('status'=>false,'message' => 'Fields Missing');
        echo json_encode($rows);
    }
    else
    {
        $folderPath = "banner/";
        $image_parts = explode(";base64,", $bannerimg);
        $image_type_aux = explode("image/", $image_parts[0]);
        $image_type = $image_type_aux[1];
        $image_base64 = base64_decode($image_parts[1]);
        $file1 = $folderPath . uniqid() . '.png';
        file_put_contents($file1, $image_base64);
            
        $sql = "UPDATE cat_banner set bimg = '$file1' where id = '$bannerid'";
        $result = mysqli_query($con,$sql);
        if($result)
        {
            $rows = array('status'=>true,'message' => 'Category Banner Updated');
            echo json_encode($rows);
        }
        
    }
}

else if($mode == "delete")
{
    if($bannerid == "")
    {
        $rows = array('status'=>false,'message' => 'Banner Error');
        echo json_encode($rows);
    }
    else
    {
        $sql = "DELETE FROM cat_banner where id ='$bannerid'";
        $result = mysqli_query($con,$sql);
        if($result)
        {
            $rows = array('status'=>true,'message' => 'Category Banner Deleted');
            echo json_encode($rows);
        }
    }
}

}

?>
