<?php
// dmanual_api_fallback.php
require_once __DIR__ . '/../../includes/database.php';

header('Content-Type: application/json; charset=utf-8');
error_reporting(0);

function send_json($data, $code = 200) {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if (!isset($conn) || !$conn) {
    send_json(['status' => 'error', 'message' => 'DB connection error'], 500);
}

if (empty($_GET['id'])) {
    send_json(['status' => 'error', 'message' => 'ID missing'], 400);
}

$raw_id = trim($_GET['id']);
$ecode  = $_GET['ecode'] ?? null;

mysqli_set_charset($conn, "utf8");

// Helper: try to fetch by a single id value (string or numeric)
function fetch_by_id($conn, $value, $ecode = null) {
    // determine param type
    $is_num = ctype_digit((string)$value);
    if (!empty($ecode)) {
        if ($is_num) {
            $sql = "SELECT * FROM dmanual WHERE id = ? AND ecode = ? LIMIT 1";
            $stmt = $conn->prepare($sql);
            if ($stmt) {
                $iv = (int)$value;
                $stmt->bind_param("is", $iv, $ecode);
            }
        } else {
            $sql = "SELECT * FROM dmanual WHERE id = ? AND ecode = ? LIMIT 1";
            $stmt = $conn->prepare($sql);
            if ($stmt) {
                $stmt->bind_param("ss", $value, $ecode);
            }
        }
    } else {
        if ($is_num) {
            $sql = "SELECT * FROM dmanual WHERE id = ? LIMIT 1";
            $stmt = $conn->prepare($sql);
            if ($stmt) {
                $iv = (int)$value;
                $stmt->bind_param("i", $iv);
            }
        } else {
            $sql = "SELECT * FROM dmanual WHERE id = ? LIMIT 1";
            $stmt = $conn->prepare($sql);
            if ($stmt) {
                $stmt->bind_param("s", $value);
            }
        }
    }

    if (!$stmt) return null;
    if (!$stmt->execute()) {
        $stmt->close();
        return null;
    }
    $res = $stmt->get_result();
    $row = $res->fetch_assoc();
    $stmt->close();
    return $row ?: null;
}

// 1) Try direct lookup using provided id
$birth = fetch_by_id($conn, $raw_id, $ecode);

// 2) If not found, and raw_id looks like base64 -> try decode and use decoded value
if (!$birth) {
    $decoded = base64_decode($raw_id, true);
    if ($decoded !== false && $decoded !== $raw_id) {
        $birth = fetch_by_id($conn, $decoded, $ecode);
        if ($birth) {
            $resolved = $decoded;
        }
    }
}

// 3) If still not found, try base64-encoding the original id and lookup
if (!$birth) {
    $encoded = base64_encode($raw_id);
    // avoid infinite loop in case base64_encode gave same string
    if ($encoded !== $raw_id) {
        $birth = fetch_by_id($conn, $encoded, $ecode);
        if ($birth) {
            $resolved = $encoded;
        }
    }
}

// If still not found, return 404
if (!$birth) {
    send_json(['status' => 'not_found', 'message' => 'Record not found'], 404);
}

// Make sure we have a resolved id string for response
if (!isset($resolved)) {
    $resolved = $raw_id;
}

// UTF8 fix for fields
array_walk_recursive($birth, function (&$val) {
    if (is_string($val)) $val = mb_convert_encoding($val, "UTF-8", "auto");
});

// Get portal row if hospital present
$portal = null;
if (!empty($birth['hospital'])) {
    $stmt2 = $conn->prepare("SELECT * FROM portal WHERE hospital = ? LIMIT 1");
    if ($stmt2) {
        $stmt2->bind_param("s", $birth['hospital']);
        $stmt2->execute();
        $portal = $stmt2->get_result()->fetch_assoc();
        $stmt2->close();
        if ($portal) {
            array_walk_recursive($portal, function (&$v) {
                if (is_string($v)) $v = mb_convert_encoding($v, 'UTF-8', 'auto');
            });
        }
    }
}

// Return JSON
send_json([
    'status'       => 'ok',
    'data'  => $birth,
    'hospital' => $portal
], 200);
