<?php 
        require_once "DBConfig.php";
 		$title = $_REQUEST['title']; 
		$category = $_REQUEST['category']; 
		$short_description = $_REQUEST['short_description']; 
		$description = $_REQUEST['description']; 
		
		$u = $_REQUEST['u'];
		$today=date("d-m-Y");
		$table = "product_table";
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_FILES["image"])) {
    $image_name = $_FILES["image"]["name"];
    $image_tmp_name = $_FILES["image"]["tmp_name"];
    $image_size = $_FILES["image"]["size"];
    $image_type = $_FILES["image"]["type"];
    $image_error = $_FILES["image"]["error"];
	$u = $_REQUEST['u'];
    // Validate file
    if ($image_error === 0) {
        if ($image_size <= 5000000) { // Max file size 5MB
            $img_ex = pathinfo($image_name, PATHINFO_EXTENSION);
            $img_ex_lc = strtolower($img_ex);

            $allowed_exs = array("jpg", "jpeg", "png", "gif", "webp");

            if (in_array($img_ex_lc, $allowed_exs)) {
                $img_upload_path = 'Blog Image/' . uniqid() . '.' . $img_ex_lc;
                move_uploaded_file($image_tmp_name, $img_upload_path);

                // Read image file into a variable
                $img_data = file_get_contents($img_upload_path);
                $img_data = $link->real_escape_string($img_data);


                $sql = "INSERT INTO $table (images,title,category,short_description,description,date_of_entry) VALUES ('$img_upload_path','$title','$category','$short_description','$description','$today')";

                if ($link->query($sql) === TRUE) {
				echo "<script type='text/javascript'> window.onload = function () { alert('Image uploaded and saved to database successfully.');	   					
				window.location.href='Products.php?u=$u';} </script>";
                   
                    // Optional: Delete the file from uploads directory
                    // unlink($img_upload_path);
                } else {
				echo "<script type='text/javascript'> window.onload = function () { alert('Error: ' . $sql . '<br>' . $link->error');	   					
				window.location.href='Products.php?u=$u';} </script>";
                   
                }
            } else {
			echo "<script type='text/javascript'> window.onload = function () { alert('You can't upload files of this type');	   					
				window.location.href='Products.php?u=$u';} </script>";
              
            }
        } else {
		echo "<script type='text/javascript'> window.onload = function () { alert('File size is too big.');	   					
				window.location.href='Products.php?u=$u';} </script>";
           
        }
    } else {
	echo "<script type='text/javascript'> window.onload = function () { alert('Error uploading file.');	   					
				window.location.href='Products.php?u=$u';} </script>";
     
    }
}

$link->close();
?>

