<?php
if (file_exists(__DIR__ . '/../config/database.php')) {
    require_once __DIR__ . '/../config/database.php';
} elseif (file_exists(__DIR__ . '/../config/config.php')) {
    require_once __DIR__ . '/../config/config.php';
} elseif (file_exists(__DIR__ . '/../config.php')) {
    require_once __DIR__ . '/../config.php';
}

// Auth checks
function isLoggedIn() {
    return isset($_SESSION['user']) && !empty($_SESSION['user']['id']);
}

function isAdmin(): bool {
    return isLoggedIn() && isset($_SESSION['user']['role']) && $_SESSION['user']['role'] === 'admin';
}

if (!function_exists('isVendor')) {
    function isVendor(): bool {
        return isLoggedIn() && isset($_SESSION['user']['role']) && $_SESSION['user']['role'] === 'vendor';
    }
}

function requireLogin() {
    if (!isLoggedIn()) {
        $_SESSION['flash_error'] = 'กรุณาเข้าสู่ระบบก่อนใช้งาน';
        header('Location: ' . SITE_URL . '/login.php');
        exit;
    }
}

function requireAdmin() {
    requireLogin();
    if (!isAdmin()) {
        $_SESSION['flash_error'] = 'คุณไม่มีสิทธิ์เข้าถึงหน้านี้ (เฉพาะ Admin เท่านั้น)';
        header('Location: ' . SITE_URL . '/index.php');
        exit;
    }
}

// CSRF Protection
function generateCSRFToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function verifyCSRFToken($token) {
    if (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
        die('CSRF token validation failed.');
    }
    return true;
}

// Brute force protection
function checkBruteForce($email) {
    $db = getDBConnection();
    $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    $stmt = $db->prepare("SELECT COUNT(*) FROM login_attempts WHERE (email = ? OR ip_address = ?) AND attempted_at > NOW() - INTERVAL 15 MINUTE");
    $stmt->execute([$email, $ip]);
    $attempts = $stmt->fetchColumn();
    return $attempts >= 5;
}

function logLoginAttempt($email) {
    $db = getDBConnection();
    $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    $stmt = $db->prepare("INSERT INTO login_attempts (ip_address, email) VALUES (?, ?)");
    $stmt->execute([$ip, $email]);
}

function resetLoginAttempts($email) {
    $db = getDBConnection();
    $ip = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
    $stmt = $db->prepare("DELETE FROM login_attempts WHERE email = ? OR ip_address = ?");
    $stmt->execute([$email, $ip]);
}

// Helper to sanitize input strings
function sanitize($data) {
    return htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
}
