<?php
// Add this to your existing includes folder
class HospitalConnector {
    private $conn;
    
    public function __construct($db_connection) {
        $this->conn = $db_connection;
    }
    
    public function getPatientHomeHospital($patient_id) {
        $query = "SELECT hr.*, phm.external_patient_id, phm.access_token 
                  FROM patient_hospital_mapping phm
                  JOIN hospital_registry hr ON phm.hospital_id = hr.hospital_id
                  WHERE phm.patient_id = $patient_id AND phm.home_hospital = 'yes'";
        $result = $this->conn->query($query);
        return $result->fetch_assoc();
    }
    
    public function getLinkedHospitals($patient_id) {
        $query = "SELECT hr.*, phm.external_patient_id 
                  FROM patient_hospital_mapping phm
                  JOIN hospital_registry hr ON phm.hospital_id = hr.hospital_id
                  WHERE phm.patient_id = $patient_id AND phm.is_active = 'yes'";
        return $this->conn->query($query);
    }
    
    public function fetchExternalRecords($hospital, $external_patient_id, $record_type = 'all') {
        if($hospital['api_endpoint']) {
            return $this->fetchViaAPI($hospital, $external_patient_id, $record_type);
        }
        return ['error' => 'No API endpoint configured'];
    }
    
    private function fetchViaAPI($hospital, $external_patient_id, $record_type) {
        $ch = curl_init($hospital['api_endpoint']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $hospital['api_key'],
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'patient_id' => $external_patient_id,
            'record_type' => $record_type,
            'hospital_code' => $hospital['hospital_code']
        ]));
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response, true);
    }
}
?>