<?php
session_start();
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

include '../include/config.php';

$doctor_id = $_SESSION['doctor_id'];
$consult_id = isset($_POST['consult_id']) ? intval($_POST['consult_id']) : 0;
$notes = isset($_POST['notes']) ? $conn->real_escape_string($_POST['notes']) : '';
$prescription = isset($_POST['prescription']) ? $conn->real_escape_string($_POST['prescription']) : '';
$diagnosis = isset($_POST['diagnosis']) ? $conn->real_escape_string($_POST['diagnosis']) : '';

if ($consult_id == 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid consultation ID']);
    exit();
}

// Check if consultation exists
$check = $conn->query("SELECT * FROM consultations WHERE id = '$consult_id' AND doctor_id = '$doctor_id'");
if ($check->num_rows == 0) {
    echo json_encode(['success' => false, 'message' => 'Consultation not found']);
    exit();
}

// Update consultation
$update = $conn->query("UPDATE consultations SET 
                            status = 'completed', 
                            notes = '$notes', 
                            prescription = '$prescription',
                            diagnosis = '$diagnosis',
                            completed_at = NOW(), 
                            ended_at = NOW() 
                        WHERE id = '$consult_id' AND doctor_id = '$doctor_id'");

if ($update) {
    // Log to engagement feed
    $conn->query("INSERT INTO doctor_engagement_feed (doctor_id, activity_type, activity_data) 
                  VALUES ('$doctor_id', 'consultation_completed', 'Completed consultation ID: $consult_id')");
    
    echo json_encode(['success' => true, 'message' => 'Consultation completed successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
}
?>