<?php
session_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';

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

$method = $_SERVER['REQUEST_METHOD'];

try {

    if ($method === 'GET') {
        $stmt = $pdo->query("SELECT * FROM patients ORDER BY created_at DESC");
        $patients = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo json_encode([
            'success' => true,
            'patients' => $patients
        ]);
    }

    elseif ($method === 'POST') {
        $name = $_POST['name'] ?? '';
        $dob = $_POST['dob'] ?? null;
        $notes = $_POST['notes'] ?? '';

        if (!$name) {
            echo json_encode(['success' => false, 'message' => 'Name required']);
            exit;
        }

        $stmt = $pdo->prepare("INSERT INTO patients (name, dob, notes) VALUES (?, ?, ?)");
        $stmt->execute([$name, $dob, $notes]);

        echo json_encode(['success' => true]);
    }

} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}