<?php
// FINAL add_product.php for the TWO-STEP SAVE
// This script assumes the file was already saved by upload_raw_image.php (Step 1).

ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'db_config.php';

$response = array();

// Set appropriate headers for API response
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

if (!isset($pdo)) {
    $response['status'] = 'error';
    $response['message'] = 'DB Connection Failed';
    echo json_encode($response);
    exit();
}

// ----------------------------------------------------
// 1. COLLECT ALL DATA FROM $_POST
// The image_path is provided by the Android app after Step 1 succeeds.
// Use null coalescing operator (??) for safe data retrieval
$name = $_POST['name'] ?? '';
$category = $_POST['category'] ?? '';
$purchase_price = $_POST['purchase_price'] ?? 0.0;
$wholesale_price = $_POST['wholesale_price'] ?? 0.0;
$retail_price = $_POST['retail_price'] ?? 0.0;
$specifications = $_POST['specifications'] ?? '';
$product_link = $_POST['product_link'] ?? '';

// CRITICAL: Get the already-saved path sent by the Android app
$image_path = $_POST['image_path'] ?? ''; 
// ----------------------------------------------------

// Basic validation for required fields
if (empty($name) || empty($category)) {
    $response['status'] = 'error';
    $response['message'] = 'Product Name and Category are required.';
    echo json_encode($response);
    exit;
}

// *** IMPORTANT: The entire old $_FILES image handling block is REMOVED ***

// 2. DATABASE INSERTION
try {
    $sql = "INSERT INTO products (name, category, purchase_price, wholesale_price, retail_price, specifications, product_link, image_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $pdo->prepare($sql);
    
    // Execute uses the path retrieved from POST
    if ($stmt->execute([
        $name, 
        $category, 
        $purchase_price, 
        $wholesale_price, 
        $retail_price, 
        $specifications, 
        $product_link, 
        $image_path // <-- The path is inserted directly here
    ])) {
        $response['status'] = 'success';
        $response['message'] = 'Product added successfully.';
        $response['saved_path_debug'] = $image_path; // Debugging info
    } else {
        $response['status'] = 'error';
        $response['message'] = 'Failed to save product to database.';
    }
} catch (PDOException $e) {
    $response['status'] = 'error';
    $response['message'] = 'Database Error: ' . $e->getMessage();
}

echo json_encode($response);
?>