
<?php
ob_start();
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', 'admin_errors.log');

// Check if user is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    error_log("Unauthorized access attempt - no admin_logged_in session");
    $_SESSION['redirect_message'] = "You must be logged in to access that page";
    header("Location: vendor-login.php");
    exit();
}

// Verify session data is complete
if (!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_email'])) {
    error_log("Incomplete session data - missing user_id or email");
    session_destroy();
    header("Location: vendor-login.php");
    exit();
}

// Database connection
require '../config/conn.php';

// Verify user exists
$user_id = $_SESSION['admin_id'];
$email = $_SESSION['admin_email'];

$stmt = $conn->prepare("SELECT * FROM admins WHERE id = ? AND email = ?");
$stmt->bind_param("is", $user_id, $email);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows !== 1) {
    error_log("User not found in database - possible session hijacking");
    session_destroy();
    header("Location: vendor-login.php");
    exit();
}

// Check for remember me token if not recently active
if (!isset($_SESSION['vendor_last_activity']) || (time() - $_SESSION['vendor_last_activity'] > 1800)) {
    if (isset($_COOKIE['remember_token'])) {
        $token = $_COOKIE['remember_token'];
        $stmt = $conn->prepare("SELECT user_id FROM remember_tokens WHERE token = ? AND expires_at > NOW()");
        $stmt->bind_param("s", $token);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 1) {
            $token_data = $result->fetch_assoc();
            if ($token_data['user_id'] == $user_id) {
                $_SESSION['vendor_last_activity'] = time();
            } else {
                session_destroy();
                setcookie('remember_token', '', time() - 3600, '/');
                header("Location: vendor-login.php");
                exit();
            }
        } else {
            session_destroy();
            setcookie('remember_token', '', time() - 3600, '/');
            header("Location: vendor-login.php");
            exit();
        }
    } else {
        session_destroy();
        header("Location: vendor-login.php");
        exit();
    }
} else {
    $_SESSION['vendor_last_activity'] = time();
}

// User is authenticated
$user = $result->fetch_assoc();
ob_end_flush();
?>