<?php

// --- Security Warning: Move these to environment variables or a secure config file outside web root ---
define('DB_HOST', "localhost");
define('DB_NAME', "digitalb_beaccurate");
define('DB_USER', "digitalb_beaccurate");
define('DB_PASS', "Saiful.1633");

define('TABLE_PRODUCTS_REQ', "Products_Req");
define('UPLOAD_DIR', "aside/uploads/requests/"); // Ensure this path is correct and writable by the web server

// --- Error Reporting for Production (log errors, don't display) ---
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/php_errors.log'); // Adjust path as needed
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED); // Log all errors except notices and deprecation warnings

// Set content type for JSON response (important for Android client)
header('Content-Type: application/json; charset=utf-8');

// Function to send JSON response and exit
function sendJsonResponse($status, $message, $data = []) {
    echo json_encode(array_merge(["status" => $status, "message" => $message], $data));
    exit;
}

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

    // Get other data from the POST request, trim whitespace
    $product_name = isset($_POST['product_name']) ? trim($_POST['product_name']) : null;
    $product_brand = isset($_POST['product_brand']) ? trim($_POST['product_brand']) : null;
    $product_category = isset($_POST['product_category']) ? trim($_POST['product_category']) : null;
    $sub_category = isset($_POST['sub_category']) ? trim($_POST['sub_category']) : null;
    $more_info = isset($_POST['more_info']) ? trim($_POST['more_info']) : null;

    // --- Barcode Handling: Set to NULL if empty or just whitespace ---
    $barcode_input = $_POST['barcode'] ?? null;
    $barcode = (empty(trim($barcode_input)) && trim($barcode_input) !== '0') ? null : trim($barcode_input);

    // --- Basic Validation ---
    if (empty($product_name)) {
        sendJsonResponse("error", "Product Name is required.");
    }

    $product_image_url = null; // Initialize to null

    // --- File Upload Handling ---
    // Define max file size (e.g., 5MB)
    $maxFileSize = 5 * 1024 * 1024; // 5 MB
    $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];

    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"]; // UPLOAD_ERR_OK
        $fileType = $file["type"]; // e.g., "image/jpeg"

        // Basic validation for file size
        if ($fileSize > $maxFileSize) {
            sendJsonResponse("error", "Image file is too large. Maximum allowed size is 5MB.");
        }

        $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        if (in_array($fileExtension, $allowedExtensions)) {
            // Validate MIME type (more secure than just extension)
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mimeType = finfo_file($finfo, $fileTmpName);
            finfo_close($finfo);

            // A more robust check might involve comparing $mimeType with expected types like 'image/jpeg', 'image/png'
            // For now, we trust the extension check and rely on the security of the upload directory.
            // if (!in_array($mimeType, ['image/jpeg', 'image/png', 'image/gif'])) {
            //     sendJsonResponse("error", "Invalid image MIME type.");
            // }

            // Generate a unique file name using a 10-character random string + timestamp
            $uniqueId = uniqid('', true); // More unique than just random string
            $newFileName = pathinfo($fileName, PATHINFO_FILENAME) . "_" . $uniqueId . "." . $fileExtension;
            $destination = UPLOAD_DIR . $newFileName;

            // Ensure upload directory exists and is writable
            if (!is_dir(UPLOAD_DIR) && !mkdir(UPLOAD_DIR, 0755, true)) {
                sendJsonResponse("error", "Failed to create upload directory.");
            }
            if (!is_writable(UPLOAD_DIR)) {
                 sendJsonResponse("error", "Upload directory is not writable. Check permissions.");
            }

            if (move_uploaded_file($fileTmpName, $destination)) {
                $product_image_url = $newFileName; // Store the filename in the database
            } else {
                error_log("Failed to move uploaded file: " . $fileTmpName . " to " . $destination . " - Error: " . $fileError);
                // We proceed without image if upload fails for non-critical reasons
                // You could send a specific error or warning if this is critical
            }
        } else {
            error_log("Invalid file type attempted for upload: " . $fileName);
            // We proceed without image if type is invalid
        }
    }

    // --- Database Connection ---
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    if ($conn->connect_error) {
        sendJsonResponse("error", "Database connection failed: " . $conn->connect_error);
    }

    // --- IMPORTANT FOR UNICODE: Set character set for the connection ---
    if (!$conn->set_charset("utf8mb4")) {
        error_log("Error loading character set utf8mb4: " . $conn->error);
        sendJsonResponse("error", "Failed to set database character set.");
    }

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

    if ($stmt === false) {
        error_log("Error preparing statement: " . $conn->error);
        $conn->close();
        sendJsonResponse("error", "Failed to prepare database statement.");
    }

    // --- Bind Parameters ---
    // All parameters are treated as strings. mysqli correctly handles PHP NULL values for 's' type.
    $types = "sssssss";
    $stmt->bind_param(
        $types,
        $product_image_url,
        $product_name,
        $product_brand,
        $product_category,
        $sub_category,
        $barcode, // This variable can now be PHP NULL
        $more_info
    );

    // --- Execute Statement ---
    if ($stmt->execute()) {
        $response_message = "New product record created successfully!";
        if ($product_image_url) {
            $response_message .= " Image uploaded as: " . $product_image_url;
        } else if (isset($_FILES["product_image"]) && $_FILES["product_image"]["error"] !== UPLOAD_ERR_NO_FILE && $_FILES["product_image"]["error"] !== UPLOAD_ERR_OK) {
            $response_message .= " Product saved, but there was an issue with the image upload.";
        } else {
            $response_message .= " No image was uploaded.";
        }
        sendJsonResponse("success", $response_message);
    } else {
        $error_message = "Error executing statement: " . $stmt->error;
        error_log("Database execution failed: " . $stmt->error . " - SQL: " . $sql . " - Data: " . json_encode($_POST));

        // If database insertion fails and image was uploaded, delete the image file
        if ($product_image_url && file_exists($destination)) {
            unlink($destination);
            $error_message .= " Uploaded image has been removed.";
        }
        sendJsonResponse("error", $error_message);
    }

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

} else {
    // Handle cases where the script is accessed directly via GET or other methods
    sendJsonResponse("error", "Please submit the product data and image via a multipart/form-data form using POST method.");
}

?>