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

// ─── CUSTOM防火墙 LOGIC INLINED FOR MULTIPART SIGNING ───
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();

// Sanitize inputs right away
$name_en = isset($_POST['name_en']) ? trim($_POST['name_en']) : '';
$name_bn = isset($_POST['name_bn']) ? trim($_POST['name_bn']) : '';

// 2. RE-CALCULATE MULTIPART SIGNATURE: Combine timestamp and plain-text fields explicitly
$expectedSignature = hash_hmac('sha256', $clientTimestamp . $name_en . $name_bn, 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 FIRWALL SECURITY BLOCKS ───

if (empty($name_en) || empty($name_bn)) {
    echo json_encode(["success" => false, "message" => "Missing localized names"]);
    exit;
}

$image_filename = "";

// Handle file uploading streams cleanly
if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
    $target_dir = "../uploads/categories/";
    
    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0755, true);
    }
    
    $file_extension = pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);
    $image_filename = "cat_" . time() . "_" . rand(1000, 9999) . "." . $file_extension;
    $target_file = $target_dir . $image_filename;
    
    if (!move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
        echo json_encode(["success" => false, "message" => "Failed to write image to disk storage"]);
        exit;
    }
} else {
    echo json_encode(["success" => false, "message" => "Category image binary is required"]);
    exit;
}

$name_en_db = $db->real_escape_string($name_en);
$name_bn_db = $db->real_escape_string($name_bn);

$insert = $db->query("INSERT INTO categories (name_en, name_bn, image, is_active) 
                      VALUES ('$name_en_db', '$name_bn_db', '$image_filename', 1)");

if ($insert) {
    echo json_encode(["success" => true, "message" => "Category inserted successfully"]);
} else {
    echo json_encode(["success" => false, "message" => $db->error]);
}