<?php
session_start();
include("../config/config.php");

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

$user_id = $_SESSION['user_id'];
$feedback_type_id = $_POST['feedback_type'];
$text = $_POST['feedback'];

// Step 1: Find department of employee
$dept_query = $con->prepare("SELECT department_id FROM users WHERE user_id=?");
$dept_query->bind_param("i", $user_id);
$dept_query->execute();
$dept_query->bind_result($department_id);
$dept_query->fetch();
$dept_query->close();

// Step 2: Get escalation level 1 user
$escalation_query = $con->prepare("
    SELECT user_id 
    FROM users 
    WHERE department_id=? AND escalation_level=1 
    LIMIT 1
");
$escalation_query->bind_param("i", $department_id);
$escalation_query->execute();
$escalation_query->bind_result($first_level_user);
$escalation_query->fetch();
$escalation_query->close();

if (empty($first_level_user)) {
    die("No escalation level 1 user assigned for this department.");
}

// Step 3: Handle file upload
$file_path = NULL;
if (isset($_FILES['feedback_file']) && $_FILES['feedback_file']['error'] == 0) {
    $upload_dir = "../uploads/feedback_files/";
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    $file_name = time() . "_" . basename($_FILES['feedback_file']['name']);
    $target_path = $upload_dir . $file_name;

    // Validate file type (optional for security)
    $allowed_types = ['image/jpeg', 'image/png', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];
    if (in_array($_FILES['feedback_file']['type'], $allowed_types)) {
        if (move_uploaded_file($_FILES['feedback_file']['tmp_name'], $target_path)) {
            $file_path = "uploads/feedback_files/" . $file_name;
        }
    }
}

// Step 4: Insert feedback record
$stmt = $con->prepare("
    INSERT INTO feedbacks (
        user_id, feedback_type_id, feedback_text, admin_id, current_level, file_path, created_at, next_escalation_time
    ) VALUES (?, ?, ?, ?, 1, ?, NOW(), DATE_ADD(NOW(), INTERVAL 24 HOUR))
");
$stmt->bind_param("iisis", $user_id, $feedback_type_id, $text, $first_level_user, $file_path);
$stmt->execute();
$stmt->close();


// Step 5: Redirect after success
header("Location: ../public/user/dashboard.php?msg=success");
exit();
?>
