<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

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

try {
    // Database connection
    $pdo = new PDO("mysql:host=localhost;dbname=bpiadvis_hb", "bpiadvis_hb", "HealthBuro2025!!");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Query: Join users and patients
    $sql = "
        SELECT 
            u.userID AS patient_id,
            u.name,
            u.phone AS contact,
            p.gender,
            TIMESTAMPDIFF(YEAR, p.dob, CURDATE()) AS age,
            p.blood_group,
            u.status
        FROM users u
        INNER JOIN patients p ON u.userID = p.userID
        ORDER BY u.userID DESC
    ";

    $stmt = $pdo->query($sql);
    $data = [];

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $data[] = [
            "patient_id" => $row['patient_id'],
            "name"       => $row['name'],
            "contact"    => $row['contact'],
            "gender"     => $row['gender'],
            "age"        => $row['age'],
            "blood_group"=> $row['blood_group'],
            "last_visit" => "Nill",
            "status"     => $row['status'],
            "actions"    => '
                <button class="btn btn-sm btn-info view-btn" data-id="'.$row['patient_id'].'">View</button>
                <button class="btn btn-sm btn-warning edit-btn" data-id="'.$row['patient_id'].'">Edit</button>
                <button class="btn btn-sm btn-danger delete-btn" data-id="'.$row['patient_id'].'">Delete</button>
            '
        ];
    }

    echo json_encode(["data" => $data]);

} catch (PDOException $e) {
    echo json_encode([
        "data" => [],
        "error" => $e->getMessage()
    ]);
}
