<?php
// FINAL update_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
// Use null coalescing operator (??) for safe data retrieval
$id = $_POST['id'] ?? 0;
$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 new/existing image path sent by the Android app
$image_path = $_POST['image_path'] ?? ''; 

// CRITICAL FOR CACHING: Generate a new timestamp (cache buster)
$last_updated = time(); // Unix timestamp
// ----------------------------------------------------

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

// 2. DATABASE UPDATE
try {
    $sql = "UPDATE products SET 
                name = ?, 
                category = ?, 
                purchase_price = ?, 
                wholesale_price = ?, 
                retail_price = ?, 
                specifications = ?, 
                product_link = ?, 
                image_path = ?,
                last_updated_at = ?  
            WHERE id = ?";
            
    $stmt = $pdo->prepare($sql);
    
    if ($stmt->execute([
        $name, 
        $category, 
        $purchase_price, 
        $wholesale_price, 
        $retail_price, 
        $specifications, 
        $product_link, 
        $image_path,
        $last_updated, // <-- CACHE BUSTER VALUE
        $id // WHERE clause
    ])) {
        // Check if any rows were affected
        if ($stmt->rowCount() > 0) {
            $response['status'] = 'success';
            $response['message'] = 'Product updated successfully.';
            $response['new_cache_key'] = $last_updated; // Return new key for client-side update
        } else {
            $response['status'] = 'warning';
            $response['message'] = 'Product data submitted but no changes were detected.';
            $response['new_cache_key'] = $last_updated; 
        }
    } else {
        $response['status'] = 'error';
        $response['message'] = 'Failed to update product in database.';
    }
} catch (PDOException $e) {
    $response['status'] = 'error';
    $response['message'] = 'Database Error: ' . $e->getMessage();
}

echo json_encode($response);
?>