<?php

// --- Database Configuration ---
// Warning: Hardcoding credentials directly in the script is not recommended for production environments.
// Consider using environment variables or a separate configuration file.
$host = "localhost";
$dbName = "accurate_be";
$userName = "accurate_be";
$pass = "Saiful.1633";

$tableName = "Products_Req";
$uploadDir = "aside/uploads/requests/"; // Ensure this path is correct and writable by the web server

// --- Data Handling (Assuming data comes via POST request from a multipart/form-data form) ---

// Check if the request method is POST and if files were uploaded
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Get other data from the POST request
    $product_name = htmlspecialchars($_POST['product_name'] ?? null);
    $product_brand = htmlspecialchars($_POST['product_brand'] ?? null);
    $product_category = htmlspecialchars($_POST['product_category'] ?? null);
    $sub_category = htmlspecialchars($_POST['sub_category'] ?? null);
    $barcode = htmlspecialchars($_POST['barcode'] ?? null);
    $more_info = htmlspecialchars($_POST['more_info'] ?? null);

    // --- Basic Validation ---
    if (empty($product_name)) {
        die("Error: Product Name is required.");
    }

    $product_image_url = null; // Initialize to null

    // --- File Upload Handling ---
    if (isset($_FILES["product_image"]) && $_FILES["product_image"]["error"] === UPLOAD_ERR_OK) {
        $file = $_FILES["product_image"];
        $fileName = $file["name"];
        $fileTmpName = $file["tmp_name"];
        $fileSize = $file["size"];
        $fileError = $file["error"];
        $fileType = $file["type"];

        $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
        $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        if (in_array($fileExtension, $allowedExtensions)) {
            // Generate a unique file name using a 10-character random string
            $randomString = substr(md5(uniqid(mt_rand(), true)), 0, 10);
            $newFileName = pathinfo($fileName, PATHINFO_FILENAME) . "_" . $randomString . "." . $fileExtension;
            $destination = $uploadDir . $newFileName;

            if (move_uploaded_file($fileTmpName, $destination)) {
                $product_image_url = $newFileName; // Store the filename in the database
            } else {
                echo "Error uploading file.";
                // Continue script execution even if image upload fails, but don't store the URL
            }
        } else {
            echo "Error: Invalid file type. Allowed types are: " . implode(", ", $allowedExtensions);
            // Continue script execution even if image upload fails due to invalid type
        }
    }

    // --- Database Connection ---
    $conn = new mysqli($host, $userName, $pass, $dbName);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // --- Prepare SQL Statement ---
    $sql = "INSERT INTO $tableName (product_image_url, product_name, product_brand, product_category, sub_category, barcode, more_info) VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);

    if ($stmt === false) {
        die("Error preparing statement: " . $conn->error);
    }

    // --- Bind Parameters ---
    $types = "sssssss"; // All parameters are strings
    $stmt->bind_param(
        $types,
        $product_image_url,
        $product_name,
        $product_brand,
        $product_category,
        $sub_category,
        $barcode,
        $more_info
    );

    // --- Execute Statement ---
    if ($stmt->execute()) {
        $message = "New product record created successfully!";
        if ($product_image_url) {
            $message .= " Image uploaded as: " . $product_image_url;
        } else {
            $message .= " No image was uploaded or there was an issue with the upload.";
        }
        echo $message;
    } else {
        echo "Error executing statement: " . $stmt->error;
        // If database insertion fails and an image was uploaded, delete it
        if ($product_image_url && file_exists($destination)) {
            unlink($destination);
        }
    }

    // --- Close Statement and Connection ---
    $stmt->close();
    $conn->close();

} else {
    // Handle cases where the script is accessed directly via GET or other methods
    echo "Please submit the product data and image via a multipart/form-data form.";
}

?>