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

if (!isset($_SESSION['doctor_id'])) {
    header("Location: login.php");
    exit();
}

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

$doctor_id = $_SESSION['doctor_id'];
$doctor_name = $_SESSION['doctor_name'];

// Get POST data
$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']) : '';
$recommendations = isset($_POST['recommendations']) ? $conn->real_escape_string($_POST['recommendations']) : '';

if ($consult_id == 0) {
    header("Location: consultations.php?error=Invalid consultation ID");
    exit();
}

// Check if consultation exists and belongs to this doctor
$check = $conn->query("SELECT c.*, p.first_name, p.last_name, p.email 
                       FROM consultations c 
                       JOIN patients p ON c.patient_id = p.patient_id 
                       WHERE c.id = '$consult_id' AND c.doctor_id = '$doctor_id'");

if ($check->num_rows == 0) {
    header("Location: consultations.php?error=Consultation not found");
    exit();
}

$consult = $check->fetch_assoc();

// Ensure consultation_fee column exists
$check_column = $conn->query("SHOW COLUMNS FROM consultations LIKE 'consultation_fee'");
if ($check_column->num_rows == 0) {
    $conn->query("ALTER TABLE consultations ADD COLUMN consultation_fee DECIMAL(10,2) DEFAULT 0");
}

// Update consultation as completed
$update_query = "UPDATE consultations SET 
                    status = 'completed', 
                    notes = '$notes', 
                    prescription = '$prescription',
                    diagnosis = '$diagnosis',
                    recommendations = '$recommendations',
                    completed_at = NOW(), 
                    ended_at = NOW() 
                WHERE id = '$consult_id' AND doctor_id = '$doctor_id'";

if ($conn->query($update_query)) {
    // Log to engagement feed
    $conn->query("INSERT INTO doctor_engagement_feed (doctor_id, activity_type, activity_data) 
                  VALUES ('$doctor_id', 'consultation_completed', 'Completed consultation with patient: " . $consult['first_name'] . " " . $consult['last_name'] . "')");
    
    // Add notification for patient (if function exists)
    if (function_exists('sendPatientNotification')) {
        $message = "Dr. $doctor_name has completed your consultation. Please check your portal for the summary and prescription.";
        sendPatientNotification($consult['patient_id'], 'Consultation Completed', $message, 'success');
    }
    
    $_SESSION['success'] = "Consultation completed successfully!";
    header("Location: consultations.php?success=completed");
    exit();
} else {
    $_SESSION['error'] = "Error completing consultation: " . $conn->error;
    header("Location: consultations.php?error=failed");
    exit();
}
?>