<?php
// Enable error display for development purposes
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Ensure a session is started
session_start();

// Include necessary files
include __DIR__ . '/../../config/config.php';
include __DIR__ . '/../../includes/functions.php';
include __DIR__ . '/../../classes/Database.php';

// Check for login and permission to delete sessions
checkLogin();
if (!hasPermission('delete_sessions')) {
    $_SESSION['error_message'] = 'ليس لديك صلاحية لإنهاء الجلسات.';
    header('Location: ' . SITE_URL . '/pages/sessions/sessions_view.php');
    exit();
}

$db = getDB();

// Get the session ID from the URL
$session_id = $_GET['id'] ?? null;

// Validate the session ID
if (!$session_id || !is_numeric($session_id)) {
    $_SESSION['error_message'] = 'معرف الجلسة غير صالح.';
    header('Location: ' . SITE_URL . '/pages/sessions/sessions_view.php');
    exit();
}

try {
    // Prepare and execute the deletion query
    $sql = "DELETE FROM user_sessions WHERE id = ?";
    $affected_rows = $db->delete($sql, [$session_id]);

    if ($affected_rows > 0) {
        $_SESSION['success_message'] = "تم إنهاء الجلسة بنجاح.";
    } else {
        $_SESSION['error_message'] = "لم يتم العثور على الجلسة أو أنها منتهية بالفعل.";
    }

} catch (Exception $e) {
    error_log("Database error deleting session: " . $e->getMessage());
    $_SESSION['error_message'] = "حدث خطأ في قاعدة البيانات أثناء إنهاء الجلسة.";
}

// Redirect back to the sessions view page
header('Location: ' . SITE_URL . '/pages/sessions/sessions_view.php');
exit();
?>