<?php
/**
 * Vendor Portal Security Check
 * Include this at the top of EVERY vendor page
 */

// Ensure session is started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Calculate relative paths dynamically based on script directory depth
$script_path = str_replace('\\', '/', $_SERVER['SCRIPT_NAME']);
$parts = explode('/vendorportal/', strtolower($script_path));
$rel_path = '';
if (isset($parts[1]) && !empty($parts[1])) {
    $depth = substr_count($parts[1], '/');
    $rel_path = str_repeat('../', $depth);
}
if (!defined('VENDOR_BASE_URL')) define('VENDOR_BASE_URL', $rel_path);
if (!defined('APP_BASE_URL')) define('APP_BASE_URL', $rel_path . '../');

// Check if vendor is logged in
if (!isset($_SESSION['vendor_id']) || empty($_SESSION['vendor_id'])) {
    header("location: ../vendor-login.php");
    exit();
}

// Get vendor details
global $con;
if (!isset($con)) {
    include_once(__DIR__ . '/../../includes/config.php');
}

// Include Security Helper
include_once(__DIR__ . '/../../includes/security.php');

// Include Unified Activity Logger
include_once(__DIR__ . '/../../includes/activity_logger.php');

$vendorId = $_SESSION['vendor_id'];
$vendorQuery = mysqli_query($con, "SELECT v.*, u.username, u.email 
                                   FROM vendors v 
                                   JOIN users u ON v.user_id = u.id 
                                   WHERE v.id = '$vendorId' LIMIT 1");

if (mysqli_num_rows($vendorQuery) > 0) {
    $vendor_data = mysqli_fetch_assoc($vendorQuery);

    // Check if vendor is still active
    if ($vendor_data['status'] != 'active') {
        session_destroy();
        header("location: ../vendor-login.php");
        exit();
    }

    // Store vendor info for easy access
    $VENDOR_INFO = [
        'id' => $vendor_data['id'],
        'user_id' => $vendor_data['user_id'],
        'store_name' => $vendor_data['store_name'],
        'store_slug' => $vendor_data['store_slug'],
        'email' => $vendor_data['email'],
        'username' => $vendor_data['username'],
        'commission_rate' => $vendor_data['commission_rate'],
        'status' => $vendor_data['status']
    ];
} else {
    session_destroy();
    header("location: ../vendor-login.php");
    exit();
}

// Set security headers
header("X-Frame-Options: SAMEORIGIN");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
?>