<?php
session_start();
require_once 'includes/config.php';

if (isset($_SESSION['user_id'])) {
    $user_id = $_SESSION['user_id'];
    
    // Clear remember token if exists
    if (isset($_COOKIE['remember_token'])) {
        $token = $_COOKIE['remember_token'];
        $sql = "DELETE FROM remember_tokens WHERE token = ?";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, "s", $token);
        mysqli_stmt_execute($stmt);
        
        // Clear cookies
        setcookie('remember_token', '', time() - 3600, '/');
        setcookie('user_id', '', time() - 3600, '/');
    }
    
    // Clear current device session
    $session_id = session_id();
    $sql = "DELETE FROM user_devices WHERE user_id = ? AND session_id = ?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, "is", $user_id, $session_id);
    mysqli_stmt_execute($stmt);
}

// Destroy session
session_destroy();

// Redirect to login
header("Location: login.php");
exit();
?>