<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
require_once 'config/database.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';
require_once 'includes/translation.php';

if (!isset($_SESSION['user_id'])) {
    redirect('login.php');
}

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: " . (isset($_SERVER["HTTPS"]) ? "https" : "http") . "://" . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER["SCRIPT_NAME"]), "/\\") . "/" . "manage_patients.php");
    exit();
}

// Get and validate type
$raw_type = isset($_GET['type']) ? $_GET['type'] : '';
$id = (int)$_GET['id'];
$type = trim(strtolower(urldecode($raw_type)));

// Reject undefined or empty type
if (empty($type) || $type === 'undefined' || $type === 'null') {
    $_SESSION['delete_message'] = "خطأ: نوع العملية غير محدد. يرجى المحاولة مرة أخرى.";
    $base = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\') . '/';
    header("Location: " . $base . "manage_patients.php");
    exit();
}

// Normalize type aliases
$type_map = [
    'patient'    => 'patient',
    'patients'   => 'patient',
    'report'     => 'report',
    'reports'    => 'report',
    'antibiotic' => 'antibiotic',
    'user'       => 'user',
    'users'      => 'user',
    'kpi'        => 'kpi',
    'kpirecord'  => 'kpi',
];
$type = $type_map[$type] ?? $type;

$redirect_page = 'manage_patients.php';

// Debug log
error_log("Delete request - type: '" . $type . "' id: " . $id . " raw_type: '" . $raw_type . "'");

$db = new Database();
$conn = $db->getConnection();

try {
    switch($type) {
        case 'report':
            // Check if report exists and user has permission
            $stmt = $conn->prepare("SELECT id FROM antibiotic_reports WHERE id = :id");
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            
            if ($stmt->rowCount() > 0) {
                // Delete related problem definitions first
                $stmt = $conn->prepare("DELETE FROM problem_definitions WHERE report_id = :id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                
                // Delete report attachments if any
                $stmt = $conn->prepare("DELETE FROM report_attachments WHERE report_id = :id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                
                // Delete the report
                $stmt = $conn->prepare("DELETE FROM antibiotic_reports WHERE id = :id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                
                // Log activity
                logActivity($conn, $_SESSION['user_id'], 'حذف تقرير', 'antibiotic_reports', $id);
                
                $redirect_page = 'reports.php';
                $message = "تم حذف التقرير بنجاح";
            } else {
                $message = "التقرير غير موجود";
            }
            break;
            
        case 'patient':
            // Check if patient exists and user has permission
            $stmt = $conn->prepare("SELECT id FROM patients WHERE id = :id");
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            
            if ($stmt->rowCount() > 0) {
                // Check if patient has reports
                $stmt = $conn->prepare("SELECT COUNT(*) as count FROM antibiotic_reports WHERE patient_id = :id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                $reportCount = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
                
                $redirect_page = 'manage_patients.php';
                
                if ($reportCount > 0) {
                    $message = "لا يمكن حذف المريض لأنه مرتبط بتقارير موجودة";
                } else {
                    // Delete the patient
                    $stmt = $conn->prepare("DELETE FROM patients WHERE id = :id");
                    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                    $stmt->execute();
                    
                    // Log activity
                    logActivity($conn, $_SESSION['user_id'], 'حذف مريض', 'patients', $id);
                    
                    $message = "تم حذف المريض بنجاح";
                }
            } else {
                $redirect_page = 'manage_patients.php';
                $message = "المريض غير موجود";
            }
            break;
            
        case 'antibiotic':
            // Check if antibiotic exists and user has permission
            if (!checkPermission('admin', $_SESSION['role'])) {
                $message = "ليس لديك صلاحية لحذف المضادات الحيوية";
                $redirect_page = 'manage_antibiotics.php';
                break;
            }
            
            $stmt = $conn->prepare("SELECT id FROM antibiotics WHERE id = :id");
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            
            $redirect_page = 'manage_antibiotics.php';
            
            if ($stmt->rowCount() > 0) {
                // Check if antibiotic has reports
                $stmt = $conn->prepare("SELECT COUNT(*) as count FROM antibiotic_reports WHERE antibiotic_id = :id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                $reportCount = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
                
                if ($reportCount > 0) {
                    // Instead of deleting, deactivate the antibiotic
                    $stmt = $conn->prepare("UPDATE antibiotics SET is_active = 0 WHERE id = :id");
                    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                    $stmt->execute();
                    
                    // Log activity
                    logActivity($conn, $_SESSION['user_id'], 'إلغاء تفعيل مضاد حيوي', 'antibiotics', $id);
                    
                    $message = "تم إلغاء تفعيل المضاد الحيوي بدلاً من حذفه لأنه مرتبط بتقارير موجودة";
                } else {
                    // Delete the antibiotic
                    $stmt = $conn->prepare("DELETE FROM antibiotics WHERE id = :id");
                    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                    $stmt->execute();
                    
                    // Log activity
                    logActivity($conn, $_SESSION['user_id'], 'حذف مضاد حيوي', 'antibiotics', $id);
                    
                    $message = "تم حذف المضاد الحيوي بنجاح";
                }
                
                $redirect_page = 'manage_antibiotics.php';
            } else {
                $message = "المضاد الحيوي غير موجود";
            }
            break;
            
        case 'kpi':
            // Check if KPI record exists
            $stmt = $conn->prepare("SELECT id, unit_id FROM patient_medication_tracking WHERE id = :id");
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            $record = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if ($record) {
                // Delete the KPI record
                $stmt = $conn->prepare("DELETE FROM patient_medication_tracking WHERE id = :id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                
                // Log activity
                logActivity($conn, $_SESSION['user_id'], 'حذف سجل KPI', 'patient_medication_tracking', $id);
                
                // Redirect back to KPI page
                $redirect_page = 'key_performance_indicators.php?unit_id=' . $record['unit_id'];
                $message = "تم حذف السجل بنجاح";
            } else {
                $redirect_page = 'key_performance_indicators.php';
                $message = "السجل غير موجود";
            }
            break;
            
        case 'user':
            // Check if user exists and current user has permission
            if (!checkPermission('admin', $_SESSION['role'])) {
                $message = "ليس لديك صلاحية لحذف المستخدمين";
                $redirect_page = 'add_user.php';
                break;
            }
            
            if ($id == $_SESSION['user_id']) {
                $message = "لا يمكنك حذف حسابك الخاص";
                $redirect_page = 'add_user.php';
                break;
            }
            
            $stmt = $conn->prepare("SELECT id FROM users WHERE id = :id");
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            
            $redirect_page = 'add_user.php';
            
            if ($stmt->rowCount() > 0) {
                // Check if user has reports
                $stmt = $conn->prepare("SELECT COUNT(*) as count FROM antibiotic_reports WHERE reporting_pharmacist_id = :id");
                $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                $stmt->execute();
                $reportCount = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
                
                if ($reportCount > 0) {
                    // Instead of deleting, deactivate the user
                    $stmt = $conn->prepare("UPDATE users SET is_active = 0 WHERE id = :id");
                    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                    $stmt->execute();
                    
                    // Log activity
                    logActivity($conn, $_SESSION['user_id'], 'إلغاء تفعيل مستخدم', 'users', $id);
                    
                    $message = "تم إلغاء تفعيل المستخدم بدلاً من حذفه لأنه مرتبط بتقارير موجودة";
                } else {
                    // Delete the user
                    $stmt = $conn->prepare("DELETE FROM users WHERE id = :id");
                    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
                    $stmt->execute();
                    
                    // Log activity
                    logActivity($conn, $_SESSION['user_id'], 'حذف مستخدم', 'users', $id);
                    
                    $message = "تم حذف المستخدم بنجاح";
                }
                
                $redirect_page = 'add_user.php';
            } else {
                $message = "المستخدم غير موجود";
            }
            break;
            
        default:
            $message = "نوع العملية غير صحيح: [" . htmlspecialchars($type) . "]";
            $redirect_page = 'manage_patients.php';
            break;
    }
    
} catch(PDOException $e) {
    error_log("Delete error: " . $e->getMessage());
    $message = "حدث خطأ أثناء عملية الحذف: " . $e->getMessage();
}

// Store message in session and redirect
$_SESSION['delete_message'] = $message;
$base = (isset($_SERVER['HTTPS']) ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/\\') . '/';
header("Location: " . $base . $redirect_page);
exit();
?>
