<?php
// tests/verify_api.php

$baseUrl = 'http://localhost:9999/api';
$dbParams = require __DIR__ . '/../layouts/dbconn.php';

function request($method, $endpoint, $data = [], $token = null)
{
    global $baseUrl;
    $url = $baseUrl . $endpoint;
    $ch = curl_init($url);

    $headers = ['Content-Type: application/json'];
    if ($token) {
        $headers[] = "Authorization: Bearer $token";
    }

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    }

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return ['code' => $httpCode, 'body' => json_decode($response, true), 'raw' => $response];
}

function test($name, $result)
{
    if ($result['code'] >= 200 && $result['code'] < 300) {
        echo "[PASS] $name\n";
    } else {
        echo "[FAIL] $name (Code: {$result['code']})\n";
        // print_r($result['body']);
    }
}

echo "Starting API Verification...\n";

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

// --- SETUP DOCTOR ---
$docUser = 'test_api_doc_' . time();
$pass = 'password123';
$hash = password_hash($pass, PASSWORD_DEFAULT);
$docRole = $conn->query("SELECT role_id FROM user_roles WHERE role_code = 'ENT_DOCTOR' LIMIT 1")->fetch_assoc()['role_id'] ?? 1;

$conn->query("INSERT INTO users (username, password_hash, email, role_id, full_name, status, is_active) 
              VALUES ('$docUser', '$hash', '$docUser@example.com', $docRole, 'Test Doctor', 'ACTIVE', 1)");
$docUserId = $conn->insert_id;
$conn->query("INSERT INTO doctors (user_id, specialization) VALUES ($docUserId, 'General ENT')");
$doctorId = $conn->insert_id;

// --- SETUP PATIENT ---
$patUser = 'test_api_pat_' . time();
$patRole = $conn->query("SELECT role_id FROM user_roles WHERE role_code = 'PATIENT' LIMIT 1")->fetch_assoc()['role_id'] ?? 1;

$conn->query("INSERT INTO users (username, password_hash, email, role_id, full_name, status, is_active, phone_primary) 
              VALUES ('$patUser', '$hash', '$patUser@example.com', $patRole, 'Test Patient', 'ACTIVE', 1, '555-0100')");
$patUserId = $conn->insert_id;
$conn->query("INSERT INTO patients (user_id, full_name, patient_number, date_of_birth, gender) 
              VALUES ($patUserId, 'Test Patient', 'P" . time() . "', '1990-01-01', 'Male')");
$patientId = $conn->insert_id;

// Add invoice for patient
$conn->query("INSERT INTO invoices (invoice_number, patient_id, invoice_date, total_amount, balance, status)
              VALUES ('INV-TEST', $patientId, NOW(), 1000.00, 1000.00, 'UNPAID')");
$invoiceId = $conn->insert_id;


// --- TEST EXECUTION ---

// 1. Doctor Login
$loginRes = request('POST', '/auth/login.php', ['username' => $docUser, 'password' => $pass]);
test("Doctor Login", $loginRes);
$docToken = $loginRes['body']['data']['token'] ?? null;

if ($docToken) {
    // 2. Doctor Appointments
    test("Doctor Get Appointments", request('GET', '/doctor/appointments.php', [], $docToken));
}

// 3. Patient Login
$loginRes = request('POST', '/auth/login.php', ['username' => $patUser, 'password' => $pass]);
test("Patient Login", $loginRes);
$patToken = $loginRes['body']['data']['token'] ?? null;

if ($patToken) {
    // 4. Patient Prescriptions
    test("Patient Get Prescriptions", request('GET', '/patient/prescriptions.php', [], $patToken));

    // 5. Patient Reports
    test("Patient Get Reports", request('GET', '/patient/reports.php', [], $patToken));

    // 6. Patient Documents
    test("Patient Get Documents", request('GET', '/patient/documents.php', [], $patToken));

    // 7. Patient Profile GET
    test("Patient Get Profile", request('GET', '/patient/profile.php', [], $patToken));

    // 8. Patient Profile UPDATE
    $updateData = [
        'full_name' => 'Test Patient Updated',
        'phone_primary' => '555-9999',
        'address' => '123 Test St'
    ];
    $updateRes = request('POST', '/patient/profile.php', $updateData, $patToken);
    test("Patient Update Profile", $updateRes);

    // 9. Patient Invoices
    test("Patient Get Invoices", request('GET', '/patient/invoices.php', [], $patToken));

    // 10. Patient Payments GET
    test("Patient Get Payments", request('GET', '/patient/payments.php', [], $patToken));

    // 11. Patient Initiate Payment
    $payData = [
        'invoice_id' => $invoiceId,
        'amount' => 500,
        'method' => 'MPESA',
        'phone' => '254700000000'
    ];
    $payRes = request('POST', '/patient/payments.php', $payData, $patToken);
    test("Patient Initiate Payment", $payRes);

    // 12. Patient Send Message
    $msgData = [
        'subject' => 'Test Subject',
        'message' => 'Test Message Body'
    ];
    $msgRes = request('POST', '/patient/messages.php', $msgData, $patToken);
    test("Patient Send Message", $msgRes);

    // 13. Patient Get Messages
    test("Patient Get Messages", request('GET', '/patient/messages.php', [], $patToken));

    // 14. Patient Get Notifications
    test("Patient Get Notifications", request('GET', '/patient/notifications.php', [], $patToken));
}


// --- CLEANUP ---
$conn->query("DELETE FROM invoices WHERE invoice_id = $invoiceId");
$conn->query("DELETE FROM medical_documents WHERE patient_id = $patientId");
$conn->query("DELETE FROM patient_messages WHERE patient_id = $patientId");
$conn->query("DELETE FROM patient_notifications WHERE patient_id = $patientId"); // Although we created none, table might exist
$conn->query("DELETE FROM doctors WHERE doctor_id = $doctorId");
$conn->query("DELETE FROM patients WHERE patient_id = $patientId");
$conn->query("DELETE FROM users WHERE user_id IN ($docUserId, $patUserId)");

echo "Cleanup completed.\n";
?>