<?php
// api/patient/profile.php
require_once __DIR__ . '/../middleware.php';
require_once __DIR__ . '/../../layouts/dbconn.php';

global $API_USER;
if (!isset($API_USER)) {
    jsonError('Unauthorized', 401);
}

// Get Patient ID
$user_id = $API_USER['sub'];
$stmt = $conn->prepare("SELECT p.patient_id FROM patients p WHERE p.user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    jsonError('Patient profile not found', 404);
}

$patient_id = $res->fetch_assoc()['patient_id'];

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Logic from patient_profile.php
    $sql = "SELECT 
                p.patient_number, p.blood_group, p.allergies, p.chronic_conditions,
                u.full_name, u.email, u.phone_primary, u.phone_secondary,
                u.gender, u.date_of_birth, u.national_id, u.address,
                u.emergency_contact_name, u.emergency_contact_phone,
                ip.provider_name, p.insurance_number, p.policy_number
            FROM patients p
            INNER JOIN users u ON p.user_id = u.user_id
            LEFT JOIN insurance_providers ip ON p.insurance_provider_id = ip.provider_id
            WHERE p.patient_id = ?";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        jsonResponse($row);
    } else {
        jsonError('Profile not found', 404);
    }

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Update Logic
    $input = json_decode(file_get_contents('php://input'), true);

    // Allowed fields to update: phone_primary, email, address, emergency contact
    // Updating users table

    $full_name = $input['full_name'] ?? null; // Might be read-only in some systems
    $email = $input['email'] ?? null;
    $phone = $input['phone_primary'] ?? null;
    $address = $input['address'] ?? null;
    $emerg_name = $input['emergency_contact_name'] ?? null;
    $emerg_phone = $input['emergency_contact_phone'] ?? null;

    if (!$full_name || !$phone) {
        jsonError('Name and Phone are required', 400);
    }

    $update = $conn->prepare("UPDATE users SET full_name=?, email=?, phone_primary=?, address=?, emergency_contact_name=?, emergency_contact_phone=? WHERE user_id=?");
    $update->bind_param("ssssssi", $full_name, $email, $phone, $address, $emerg_name, $emerg_phone, $user_id);

    if ($update->execute()) {
        // Also update medical info in patients table if provided?
        // Usually medical info is doctor managed, but let's allow updating allergies if provided
        if (isset($input['allergies'])) {
            $p_update = $conn->prepare("UPDATE patients SET allergies=? WHERE patient_id=?");
            $p_update->bind_param("si", $input['allergies'], $patient_id);
            $p_update->execute();
        }

        jsonResponse(['message' => 'Profile updated successfully']);
    } else {
        jsonError('Update failed: ' . $conn->error, 500);
    }

} else {
    jsonError('Method not allowed', 405);
}
?>