<?php

session_start();

if (isset($_SESSION['user_email'])){

require '../../config.php';
require '../functions.php';

$connect = connect($database);

$check_access = check_access($connect);

if ($check_access['user_role'] == 1){

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        $ip_address = trim($_POST['ip_address']);
        $reason = trim($_POST['reason']);
        $ban_type = $_POST['ban_type'];
        $duration_days = isset($_POST['duration_days']) ? intval($_POST['duration_days']) : 0;
        
        $is_permanent = ($ban_type == 'permanent') ? 1 : 0;
        $expires_at = null;
        
        if (!$is_permanent && $duration_days > 0) {
            $expires_at = date('Y-m-d H:i:s', strtotime("+{$duration_days} days"));
        }
        
        // Check if IP already banned
        $check = $connect->prepare("SELECT ban_id FROM banned_ips WHERE ip_address = :ip");
        $check->execute([':ip' => $ip_address]);
        
        if ($check->fetch()) {
            // Update existing ban
            $update = $connect->prepare("UPDATE banned_ips SET reason = :reason, is_permanent = :permanent, expires_at = :expires, banned_by = :user, banned_at = NOW() WHERE ip_address = :ip");
            $update->execute([
                ':reason' => $reason,
                ':permanent' => $is_permanent,
                ':expires' => $expires_at,
                ':user' => $check_access['user_id'],
                ':ip' => $ip_address
            ]);
        } else {
            // Insert new ban
            $insert = $connect->prepare("INSERT INTO banned_ips (ip_address, reason, banned_by, is_permanent, expires_at) VALUES (:ip, :reason, :user, :permanent, :expires)");
            $insert->execute([
                ':ip' => $ip_address,
                ':reason' => $reason,
                ':user' => $check_access['user_id'],
                ':permanent' => $is_permanent,
                ':expires' => $expires_at
            ]);
        }
        
        header('Location: ./banned_ips.php?success=banned');
        exit;
    }
    
    $ip_address = isset($_GET['ip']) ? $_GET['ip'] : '';

    require '../views/header.view.php';
    require '../views/ban_ip.view.php';

}else{
    header('Location:'.SITE_URL);
}

require '../views/footer.view.php';

}else {
    header('Location: ./login.php');		
}

?>
