<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', 1);

// ─── INLINED MULTIPART SIGNATURE FIREWALL ───
define('SECRET_SIGNATURE_KEY', 'GlobInvestAdminSecureKey2026#TokenPlatform');

$headers = getallheaders();
$clientSignature = $headers['X-Signature'] ?? $headers['x-signature'] ?? '';
$clientTimestamp = $headers['X-Timestamp'] ?? $headers['x-timestamp'] ?? '';

if (empty($clientSignature) || empty($clientTimestamp)) {
    header("HTTP/1.1 401 Unauthorized");
    echo json_encode(["success" => false, "message" => "Security Headers Missing"]);
    exit;
}

$serverTimestamp = time();
if (abs($serverTimestamp - intval($clientTimestamp)) > 300) {
    header("HTTP/1.1 403 Forbidden");
    echo json_encode(["success" => false, "message" => "Request Expired. Sync your device clock."]);
    exit;
}

require_once '../config/database.php';
$db = getDB();

// Gather primary alignment values from the multipart stream
$product_id  = isset($_POST['id']) ? intval($_POST['id']) : 0;
$name_en     = isset($_POST['name_en']) ? trim($_POST['name_en']) : '';
$category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;
$price       = isset($_POST['price']) ? floatval($_POST['price']) : 0;

if ($product_id <= 0) {
    echo json_encode(["success" => false, "message" => "Missing target product reference ID"]);
    exit;
}

// Convert price float to a clean rounded string sequence matching Flutter
$price_fixed_str = number_format($price, 0, '', '');

// 2. CRYPTO HANDSHAKE MATCH: timestamp + nameEn + categoryId + price + productId
$expectedSignature = hash_hmac('sha256', $clientTimestamp . $name_en . $category_id . $price_fixed_str . $product_id, SECRET_SIGNATURE_KEY);

if (!hash_equals($expectedSignature, $clientSignature)) {
    header("HTTP/1.1 403 Forbidden");
    echo json_encode(["success" => false, "message" => "Invalid Security Signature Hash"]);
    exit;
}
// ─── END OF FIREWALL SECURITY BLOCKS ───

$name_bn        = $db->real_escape_string($_POST['name_bn'] ?? '');
$name_en_db     = $db->real_escape_string($name_en);
$desc_en        = $db->real_escape_string($_POST['description_en'] ?? '');
$desc_bn        = $db->real_escape_string($_POST['description_bn'] ?? '');
$old_price      = isset($_POST['old_price']) ? floatval($_POST['old_price']) : "NULL";
$stock          = intval($_POST['stock'] ?? 0);
$is_featured    = intval($_POST['is_featured'] ?? 0);
$is_active      = intval($_POST['is_active'] ?? 1);

$sections_json  = $_POST['sections'] ?? '[]';
$sections       = json_decode($sections_json, true);

// Check if new images are uploaded
$uploaded_images = [];
if (isset($_FILES['images']) && count($_FILES['images']['name']) > 0 && $_FILES['images']['error'][0] != UPLOAD_ERR_NO_FILE) {
    $target_dir = "../uploads/products/";
    $file_count = count($_FILES['images']['name']);
    for ($i = 0; $i < $file_count; $i++) {
        if ($_FILES['images']['error'][$i] == UPLOAD_ERR_OK) {
            $ext = pathinfo($_FILES["images"]["name"][$i], PATHINFO_EXTENSION);
            $filename = "prod_" . time() . "_" . $i . "_" . rand(1000, 9999) . "." . $ext;
            if (move_uploaded_file($_FILES["images"]["tmp_name"][$i], $target_dir . $filename)) {
                $uploaded_images[] = $filename;
            }
        }
    }
}

$old_price_val = ($old_price === "NULL" || empty($_POST['old_price'])) ? "NULL" : "'$old_price'";

// Build core query update segment
if (!empty($uploaded_images)) {
    $images_db_value = $db->real_escape_string(json_encode($uploaded_images));
    $updateQuery = "UPDATE products SET category_id = $category_id, name_en = '$name_en_db', name_bn = '$name_bn', description_en = '$desc_en', description_bn = '$desc_bn', price = $price, old_price = $old_price_val, stock = $stock, images = '$images_db_value', is_featured = $is_featured, is_active = $is_active WHERE id = $product_id";
} else {
    $updateQuery = "UPDATE products SET category_id = $category_id, name_en = '$name_en_db', name_bn = '$name_bn', description_en = '$desc_en', description_bn = '$desc_bn', price = $price, old_price = $old_price_val, stock = $stock, is_featured = $is_featured, is_active = $is_active WHERE id = $product_id";
}

if (!$db->query($updateQuery)) {
    echo json_encode(["success" => false, "message" => "Product modification error: " . $db->error]);
    exit;
}

// Re-map section relations cleanly by dropping old entries and inserting new selections
$db->query("DELETE FROM section_products WHERE product_id = $product_id");
if (!empty($sections) && is_array($sections)) {
    $values_array = [];
    foreach ($sections as $section_id) {
        $sec_id = intval($section_id);
        if ($sec_id > 0) {
            $values_array[] = "($sec_id, $product_id)";
        }
    }
    if (!empty($values_array)) {
        $relation_query = "INSERT INTO section_products (section_id, product_id) VALUES " . implode(',', $values_array);
        $db->query($relation_query);
    }
}

echo json_encode(["success" => true, "message" => "Product update synchronized successfully"]);