<?php
session_start();
include '../layouts/dbconn.php';
include '../layouts/session.php';

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

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

// Only SUPER_ADMIN and HOSPITAL_ADMIN may delete procedures
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Access denied. Only administrators can delete procedures.']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$procedure_id = (int)($_POST['procedure_id'] ?? 0);
$reason       = trim($_POST['reason'] ?? '');

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

if (empty($reason)) {
    echo json_encode(['success' => false, 'message' => 'A reason is required to delete a procedure']);
    exit();
}

// ── Load the procedure ────────────────────────────────────────────────────────
$stmt = $conn->prepare(
    "SELECT pp.procedure_id, pp.procedure_number, pp.status,
            pp.patient_id, pp.visit_id,
            COALESCE(pp.scheduled_patient_name, u.full_name) AS patient_name,
            ept.procedure_name,
            pp.procedure_date
     FROM patient_procedures pp
     INNER JOIN ent_procedure_types ept ON pp.procedure_type_id = ept.procedure_type_id
     LEFT JOIN patients p ON pp.patient_id = p.patient_id
     LEFT JOIN users    u ON p.user_id = u.user_id
     WHERE pp.procedure_id = ?"
);
$stmt->bind_param('i', $procedure_id);
$stmt->execute();
$proc = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$proc) {
    echo json_encode(['success' => false, 'message' => 'Procedure not found']);
    exit();
}

if ($proc['is_deleted']) {
    echo json_encode(['success' => false, 'message' => 'Procedure has already been deleted']);
    exit();
}

// ── Soft delete ───────────────────────────────────────────────────────────────
$user_id = (int)$_SESSION['user_id'];
$del_stmt = $conn->prepare(
    "UPDATE patient_procedures
     SET is_deleted    = 1,
         deleted_at    = NOW(),
         deleted_by    = ?,
         delete_reason = ?
     WHERE procedure_id = ?"
);
$del_stmt->bind_param('isi', $user_id, $reason, $procedure_id);
$del_stmt->execute();
$del_stmt->close();

// ── Audit log ─────────────────────────────────────────────────────────────────
$proc_num  = $proc['procedure_number'] ?? "ID#{$procedure_id}";
$proc_name = $proc['procedure_name'] ?? 'Unknown';
$pat_name  = $proc['patient_name']   ?? 'Unknown';
$proc_date = $proc['procedure_date'] ?? '';
$log_desc  = "Deleted procedure {$proc_num} ({$proc_name}) for patient '{$pat_name}'"
           . ($proc_date ? " dated {$proc_date}" : '')
           . ". Status was: {$proc['status']}. Reason: {$reason}";

$ip = $_SERVER['REMOTE_ADDR'] ?? '';
$log_stmt = $conn->prepare(
    "INSERT INTO activity_logs
        (user_id, action, entity_type, entity_id, description, ip_address, status)
     VALUES (?, 'DELETE', 'PROCEDURE', ?, ?, ?, 'SUCCESS')"
);
$log_stmt->bind_param('iiss', $user_id, $procedure_id, $log_desc, $ip);
$log_stmt->execute();
$log_stmt->close();

echo json_encode([
    'success' => true,
    'message' => "Procedure {$proc_num} has been deleted and audit logged."
]);
