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

// ─── CUSTOM 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;
}

// 1. Prevent Replay Exploits
$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 target inputs natively via $_POST arrays
$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;

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

// 2. ✅ SYNCHRONIZED CRYPTO HANDSHAKE MATCH: timestamp + nameEn + categoryId + price (as fixed int)
$expectedSignature = hash_hmac('sha256', $clientTimestamp . $name_en . $category_id . $price_fixed_str, 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 ───

// Sanitize other remaining payload text entries safely
$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);

if (empty($name_en) || empty($name_bn) || $category_id <= 0) {
    echo json_encode(["success" => false, "message" => "Missing required core information parameters"]);
    exit;
}

$uploaded_images = [];

// Handle multiple showcase catalog file items uploads
if (isset($_FILES['images'])) {
    $target_dir = "../uploads/products/";
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0755, true);
    }
    
    $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;
            }
        }
    }
}

$images_db_value = $db->real_escape_string(json_encode($uploaded_images));
$old_price_val = ($old_price === "NULL" || empty($_POST['old_price'])) ? "NULL" : "'$old_price'";

// Save to core inventory records
$productQuery = "INSERT INTO products (category_id, name_en, description_en, price, old_price, stock, images, is_featured, is_active, name_bn, description_bn, total_sales, avg_rating, review_count) 
                 VALUES ($category_id, '$name_en_db', '$desc_en', $price, $old_price_val, $stock, '$images_db_value', $is_featured, $is_active, '$name_bn', '$desc_bn', 0, 0.00, 0)";

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

$new_product_id = $db->insert_id;

// Update relational homepage showcase lists rows
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, $new_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 with multi-section maps saved cleanly", "product_id" => $new_product_id]);