<?php
include("../../includes/auth_check.php");
include("../../config/config.php");

if ($_SESSION['role'] != 'employee') die("Access denied");

$user_id = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $feedback_id = $_POST['feedback_id'];
    $feedback_text = trim($_POST['feedback_text']);

    // Fetch old grievance + employee department
    $sql = "SELECT f.*, u.department_id 
            FROM feedbacks f 
            JOIN users u ON f.user_id = u.user_id 
            WHERE f.feedback_id = ? AND f.user_id = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param("ii", $feedback_id, $user_id);
    $stmt->execute();
    $old = $stmt->get_result()->fetch_assoc();

    if (!$old) die("Invalid grievance");

    $department_id = $old['department_id'];

    // Find next-level admin (Level 2)
    $admin_sql = "SELECT user_id FROM users 
                  WHERE department_id = ? AND escalation_level = 2 LIMIT 1";
    $admin_stmt = $con->prepare($admin_sql);
    $admin_stmt->bind_param("i", $department_id);
    $admin_stmt->execute();
    $admin_res = $admin_stmt->get_result()->fetch_assoc();

    if (!$admin_res) die("No Level 2 admin found for this department.");

    $next_admin_id = $admin_res['user_id'];

    // Handle file upload
    $file_path = $old['file_path'];
    if (!empty($_FILES['file_path']['name'])) {
        $uploadDir = "../../uploads/grievances/";
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

        $fileName = time() . "_" . basename($_FILES['file_path']['name']);
        $targetFile = $uploadDir . $fileName;
        move_uploaded_file($_FILES['file_path']['tmp_name'], $targetFile);
        $file_path = "uploads/grievances/" . $fileName;
    }

    // Insert new grievance (Level 2)
    $insert = "INSERT INTO feedbacks 
               (user_id, feedback_type_id, feedback_text, file_path, status, admin_id, current_level, created_at)
               VALUES (?, ?, ?, ?, 'pending', ?, 2, NOW())";
    $stmt = $con->prepare($insert);
    $stmt->bind_param("iissi", 
        $user_id, 
        $old['feedback_type_id'], 
        $feedback_text, 
        $file_path, 
        $next_admin_id
    );
    $stmt->execute();

    // Mark old grievance as resubmitted
    $con->query("UPDATE feedbacks SET status = 'resubmitted' WHERE feedback_id = $feedback_id");

    header("Location: my_feedback.php?msg=resubmitted");
    exit;
}
?>
