<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/Inventory.php';
require_once __DIR__ . '/../classes/Notifications.php';

session_start();
if (empty($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Login required.']);
    exit;
}

$uniqueCode = trim((string)($_POST['unique_code'] ?? ''));
if ($uniqueCode === '') {
    echo json_encode(['success' => false, 'message' => 'Missing unique code.']);
    exit;
}

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$inventory = new Inventory($conn);
$notifications = new Notifications($conn);

$item = $inventory->getItemByUniqueCode($uniqueCode);
if (!$item) {
    echo json_encode(['success' => false, 'message' => 'Item not found.']);
    exit;
}

$branchId = (int)($item['current_location_id'] ?? 0);
$branchStmt = $conn->prepare('SELECT branch_name FROM branches WHERE branch_id = :branch_id');
$branchStmt->execute([':branch_id' => $branchId]);
$branchName = $branchStmt->fetchColumn() ?: 'Unknown branch';
$reportedBy = $_SESSION['username'] ?? ('user #' . (int)$_SESSION['user_id']);

$message = "Item {$item['item_name']} (unique_code: {$uniqueCode}) at {$branchName} is not mapped to an MRA EIS product batch and cannot be sold. "
    . "Reported by {$reportedBy}. Go to Admin \xE2\x86\x92 EIS Stock Batch Mapping to assign it.";

$notificationId = $notifications->createNotification($branchId, $message, 'Admin');

echo json_encode(['success' => (bool)$notificationId]);
