<?php
/**
 * Soft-delete doctor: set is_active = 0 and users.status = 'INACTIVE'.
 * Does not remove records (preserves appointments/consultations history).
 */
error_reporting(E_ALL);
ini_set('display_errors', 0);
session_start();
require_once __DIR__ . '/../layouts/dbconn.php';

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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
$role_sql = "SELECT ur.role_code FROM users u INNER JOIN user_roles ur ON u.role_id = ur.role_id WHERE u.user_id = ?";
$stmt_r = $conn->prepare($role_sql);
$stmt_r->bind_param("i", $_SESSION['user_id']);
$stmt_r->execute();
$role = $stmt_r->get_result()->fetch_assoc()['role_code'] ?? '';
$stmt_r->close();
if (!in_array($role, $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

$doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;

if (!$doctor_id) {
    echo json_encode(['success' => false, 'message' => 'Invalid doctor ID']);
    exit();
}

try {
    $conn->begin_transaction();

    $stmt_doc = $conn->prepare("SELECT user_id FROM doctors WHERE doctor_id = ?");
    if (!$stmt_doc) {
        throw new Exception('Database prepare error: ' . $conn->error);
    }
    $stmt_doc->bind_param("i", $doctor_id);
    $stmt_doc->execute();
    $result = $stmt_doc->get_result();
    $row = $result->fetch_assoc();
    $stmt_doc->close();
    
    if (!$row) {
        $conn->rollback();
        echo json_encode(['success' => false, 'message' => 'Doctor not found']);
        exit();
    }
    $user_id = (int) $row['user_id'];

    $stmt_doc_upd = $conn->prepare("UPDATE doctors SET is_active = 0 WHERE doctor_id = ?");
    if (!$stmt_doc_upd) {
        throw new Exception('Database prepare error: ' . $conn->error);
    }
    $stmt_doc_upd->bind_param("i", $doctor_id);
    if (!$stmt_doc_upd->execute()) {
        $stmt_doc_upd->close();
        throw new Exception('Failed to update doctor: ' . $stmt_doc_upd->error);
    }
    $stmt_doc_upd->close();

    $stmt_u = $conn->prepare("UPDATE users SET status = 'INACTIVE' WHERE user_id = ?");
    if (!$stmt_u) {
        throw new Exception('Database prepare error: ' . $conn->error);
    }
    $stmt_u->bind_param("i", $user_id);
    if (!$stmt_u->execute()) {
        $stmt_u->close();
        throw new Exception('Failed to update user: ' . $stmt_u->error);
    }
    $stmt_u->close();

    $conn->commit();
    echo json_encode(['success' => true, 'message' => 'Doctor has been deactivated and removed from active lists.']);
} catch (Exception $e) {
    if ($conn->in_transaction) {
        $conn->rollback();
    }
    error_log('delete_doctor.php error: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
