<?php
/**
 * إعدادات الأمان - CSRF، Rate Limiting، الجلسات
 */

// إنشاء توكن CSRF
function csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// حقل مخفي للتوكن
function csrf_field() {
    return '<input type="hidden" name="csrf_token" value="' . htmlspecialchars(csrf_token()) . '">';
}

// التحقق من التوكن
function csrf_verify() {
    $token = $_POST['csrf_token'] ?? $_GET['csrf_token'] ?? $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
    return !empty($token) && hash_equals($_SESSION['csrf_token'] ?? '', $token);
}

// التحقق والإيقاف إن فشل
function require_csrf() {
    $must_verify = false;
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $must_verify = true;
    } elseif ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'delete') {
        $must_verify = true;
    }
    if ($must_verify && !csrf_verify()) {
        if (strpos($_SERVER['HTTP_ACCEPT'] ?? '', 'application/json') !== false || isset($_GET['action'])) {
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode(['success' => false, 'message' => 'انتهت صلاحية الجلسة. حدّث الصفحة وحاول مجدداً.']);
        } else {
            die('خطأ أمني: توكن غير صالح. حدّث الصفحة وحاول مجدداً.');
        }
        exit;
    }
}

// Rate limiting لتسجيل الدخول
function login_attempts_check() {
    global $conn;
    if (!isset($conn)) return ['allowed' => true, 'message' => ''];
    
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $max_attempts = 5;
    $lockout_minutes = 15;
    
    $r = @$conn->query("SHOW TABLES LIKE 'login_attempts'");
    if (!$r || $r->num_rows == 0) return ['allowed' => true, 'message' => ''];
    
    $stmt = $conn->prepare("SELECT attempts, locked_until FROM login_attempts WHERE ip_address = ?");
    $stmt->bind_param("s", $ip);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    
    if ($row) {
        $locked = $row['locked_until'] && strtotime($row['locked_until']) > time();
        if ($locked) {
            $mins = ceil((strtotime($row['locked_until']) - time()) / 60);
            return ['allowed' => false, 'message' => "تم قفل المحاولات. انتظر $mins دقيقة."];
        }
        if ((int)$row['attempts'] >= $max_attempts) {
            $until = date('Y-m-d H:i:s', strtotime("+$lockout_minutes minutes"));
            $st = $conn->prepare("UPDATE login_attempts SET attempts = 0, locked_until = ? WHERE ip_address = ?");
            $st->bind_param("ss", $until, $ip);
            $st->execute();
            return ['allowed' => false, 'message' => "تجاوزت الحد. انتظر $lockout_minutes دقيقة."];
        }
    }
    return ['allowed' => true, 'message' => ''];
}

function login_attempt_fail() {
    global $conn;
    if (!isset($conn)) return;
    
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $stmt = $conn->prepare("INSERT INTO login_attempts (ip_address, attempts, last_attempt) VALUES (?, 1, NOW()) 
        ON DUPLICATE KEY UPDATE attempts = attempts + 1, locked_until = NULL, last_attempt = NOW()");
    $stmt->bind_param("s", $ip);
    $stmt->execute();
}

function login_attempt_success() {
    global $conn;
    if (!isset($conn)) return;
    
    $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    $st = $conn->prepare("DELETE FROM login_attempts WHERE ip_address = ?");
    $st->bind_param("s", $ip);
    $st->execute();
}
