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

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 input parameters
$category_id = isset($_POST['id']) ? intval($_POST['id']) : 0;
$name_en = isset($_POST['name_en']) ? trim($_POST['name_en']) : '';
$name_bn = isset($_POST['name_bn']) ? trim($_POST['name_bn']) : '';

if (!$category_id) {
    echo json_encode(["success" => false, "message" => "Category ID required for editing"]);
    exit;
}

// Security Signature matching rules precisely mimicking your custom add configuration setup
$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;
}

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

// Check current existing row data to preserve old filename if no new asset is sent
$stmt = $db->query("SELECT image FROM categories WHERE id = $category_id");
if (!$stmt || $stmt->num_rows === 0) {
    echo json_encode(["success" => false, "message" => "Category target not found"]);
    exit;
}
$current_category = $stmt->fetch_assoc();
$image_filename = $current_category['image'];

// Process uploading optional replacement image files
if (isset($_FILES['image']) && $_FILES['image']['error'] == UPLOAD_ERR_OK) {
    $target_dir = "../uploads/categories/";
    
    // Clean up old image asset file from disk if it exists
    if (!empty($image_filename) && file_exists($target_dir . $image_filename)) {
        @unlink($target_dir . $image_filename);
    }
    
    $file_extension = pathinfo($_FILES["image"]["name"], PATHINFO_EXTENSION);
    $image_filename = "cat_" . time() . "_" . rand(1000, 9999) . "." . $file_extension;
    
    if (!move_uploaded_file($_FILES["image"]["tmp_name"], $target_dir . $image_filename)) {
        echo json_encode(["success" => false, "message" => "Failed to write image to disk storage"]);
        exit;
    }
}

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

$update = $db->query("UPDATE categories 
                      SET name_en = '$name_en_db', name_bn = '$name_bn_db', image = '$image_filename' 
                      WHERE id = $category_id");

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