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

require_once __DIR__ . '/../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$allowed = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'] ?? '', $allowed)) {
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

if (!isset($_POST['action']) || $_POST['action'] !== 'add_mapping') {
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    exit;
}

$user_id = (int) ($_POST['user_id'] ?? 0);
$device_id = (int) ($_POST['device_id'] ?? 0);
$zk_user_id = trim($_POST['zk_user_id'] ?? '');
$zk_badge_no = trim($_POST['zk_badge_no'] ?? $zk_user_id);

if ($user_id <= 0 || $device_id <= 0 || $zk_user_id === '') {
    echo json_encode(['success' => false, 'message' => 'User, device and PIN are required']);
    exit;
}

$stmt = $conn->prepare("INSERT INTO user_zk_mapping (user_id, device_id, zk_user_id, zk_badge_no) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE zk_user_id = ?, zk_badge_no = ?");
$stmt->bind_param("iissss", $user_id, $device_id, $zk_user_id, $zk_badge_no, $zk_user_id, $zk_badge_no);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Mapping saved']);
} else {
    echo json_encode(['success' => false, 'message' => 'Save failed. Ensure device and user exist.']);
}
