<?php
session_start();
include 'includes/auth.php';
include 'includes/db.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $member_id = isset($_POST['member_id']) ? (int)$_POST['member_id'] : 0;
    $reason = isset($_POST['reason']) ? mysqli_real_escape_string($conn, $_POST['reason']) : '';
    $details = isset($_POST['details']) ? mysqli_real_escape_string($conn, $_POST['details']) : '';
    $action_required = isset($_POST['action_required']) ? mysqli_real_escape_string($conn, $_POST['action_required']) : '';
    $consequences = isset($_POST['consequences']) ? mysqli_real_escape_string($conn, $_POST['consequences']) : '';
    $issued_by = isset($_POST['issued_by']) ? mysqli_real_escape_string($conn, $_POST['issued_by']) : 'Admin';

    // Check if member exists
    $member = mysqli_fetch_assoc(mysqli_query($conn, "SELECT first_name, surname FROM members WHERE id = $member_id"));
    if (!$member) {
        $_SESSION['warning_message'] = 'Member not found.';
        header('Location: warnings.php');
        exit;
    }

    // Get current warning count
    $count_result = mysqli_query($conn, "SELECT COUNT(*) as total FROM warnings WHERE member_id = $member_id");
    $count_data = mysqli_fetch_assoc($count_result);
    $warning_count = (int)$count_data['total'];

    // Determine next warning level
    $warning_levels = ['First', 'Second', 'Final'];
    if ($warning_count >= 3) {
        $_SESSION['warning_message'] = 'Member already has the maximum number of warnings.';
        header('Location: warnings.php');
        exit;
    }
    $next_level = $warning_levels[$warning_count];

    // Insert new warning
    $stmt = $conn->prepare("INSERT INTO warnings (member_id, warning_level, reason, details, action_required, consequences, issued_by, issued_date) VALUES (?, ?, ?, ?, ?, ?, ?, CURDATE())");
    $stmt->bind_param("issssss", $member_id, $next_level, $reason, $details, $action_required, $consequences, $issued_by);

    if ($stmt->execute()) {
        $_SESSION['warning_message'] = "Warning ($next_level) issued successfully for {$member['first_name']} {$member['surname']}.";
    } else {
        $_SESSION['warning_message'] = 'Failed to issue warning.';
    }
    $stmt->close();
    header('Location: warnings.php');
    exit;
} else {
    $_SESSION['warning_message'] = 'Invalid request.';
    header('Location: warnings.php');
    exit;
}
?>
