<?php
session_start();
include 'config.php';

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Debug: Log session data
error_log("Respond Grievance - Session data: " . print_r($_SESSION, true), 3, "debug.log");
error_log("Respond Grievance - Session ID: " . session_id() . ", Status: " . session_status(), 3, "debug.log");

// Ensure only Admins and Super Admins can access this page
$valid_roles = ['super admin', 'admin', 'superadmin'];
if (!isset($_SESSION['username']) || !in_array(strtolower($_SESSION['role'] ?? ''), $valid_roles)) {
    $error_message = "Respond Grievance - Access denied: username=" . ($_SESSION['username'] ?? 'not set') . ", role=" . ($_SESSION['role'] ?? 'not set');
    error_log($error_message, 3, "debug.log");
    die("Access denied: $error_message");
}

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    error_log("Respond Grievance - Invalid grievance ID: " . ($_GET['id'] ?? 'not set'), 3, "debug.log");
    echo "Invalid grievance ID.";
    exit();
}

$grievance_id = (int)$_GET['id'];

// Fetch grievance details (using new columns)
$grievance_sql = "SELECT g.id, g.title, g.description, g.status, g.user_id, g.created_at, g.hr_reply, u.username 
                  FROM grievances g 
                  LEFT JOIN users u ON g.user_id = u.id 
                  WHERE g.id = ?";
$stmt = $conn->prepare($grievance_sql);
if (!$stmt) {
    error_log("Respond Grievance - Prepare failed: " . $conn->error, 3, "debug.log");
    echo "Database error: " . $conn->error;
    exit();
}
$stmt->bind_param("i", $grievance_id);
$stmt->execute();
$grievance_result = $stmt->get_result();
$grievance = $grievance_result->fetch_assoc();

if (!$grievance) {
    error_log("Respond Grievance - No grievance found for ID: " . $grievance_id, 3, "debug.log");
    echo "No grievance found!";
    exit();
}

// Handle grievance response submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $response = trim($_POST['response'] ?? '');
    
    if (empty($response)) {
        error_log("Respond Grievance - Response is empty for grievance ID: " . $grievance_id, 3, "debug.log");
        echo "Response cannot be empty!";
        exit();
    }

    // Update using new hr_reply + status
    $update_sql = "UPDATE grievances SET hr_reply = ?, status = 'Resolved' WHERE id = ?";
    $stmt = $conn->prepare($update_sql);
    if (!$stmt) {
        error_log("Respond Grievance - Update prepare failed: " . $conn->error, 3, "debug.log");
        echo "Database error: " . $conn->error;
        exit();
    }
    $stmt->bind_param("si", $response, $grievance_id);
    
    if ($stmt->execute()) {
        error_log("Respond Grievance - Grievance ID $grievance_id responded successfully", 3, "debug.log");
        header("Location: grievance_dashboard.php");
        exit();
    } else {
        error_log("Respond Grievance - Error responding to grievance ID $grievance_id: " . $conn->error, 3, "debug.log");
        echo "Error responding to grievance: " . $conn->error;
    }
}

// Check if header.php exists
if (file_exists('header.php')) {
    include 'header.php';
} else {
    // Fallback header
    echo '<!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8">
              <meta name="viewport" content="width=device-width, initial-scale=1.0">
              <title>Respond to Grievance</title>
              <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
          </head>
          <body>';
}
?>

<div class="container mt-4">
    <h1 class="text-primary text-center">Respond to Grievance</h1>
    <div class="card mt-4">
        <div class="card-header bg-warning text-dark">
            <h2>Grievance from <?php echo htmlspecialchars($grievance['username'] ?? 'Unknown User', ENT_QUOTES, 'UTF-8'); ?></h2>
        </div>
        <div class="card-body">
            <p><strong>Title:</strong> <?php echo htmlspecialchars($grievance['title'], ENT_QUOTES, 'UTF-8'); ?></p>
            <p><strong>Description:</strong> <?php echo htmlspecialchars($grievance['description'], ENT_QUOTES, 'UTF-8'); ?></p>
            <p><strong>Posted On:</strong> <?php echo date('M d, Y h:i A', strtotime($grievance['created_at'])); ?></p>
            <form method="POST">
                <div class="form-group">
                    <label for="response">Response</label>
                    <textarea id="response" name="response" class="form-control" rows="5" required><?php echo htmlspecialchars($grievance['hr_reply'] ?? '', ENT_QUOTES, 'UTF-8'); ?></textarea>
                </div>
                <button type="submit" class="btn btn-primary mt-2">Submit Response</button>
            </form>
        </div>
    </div>
</div>

<?php
// Check if footer.php exists
if (file_exists('footer.php')) {
    include 'footer.php';
} else {
    // Fallback footer
    echo '<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
          </body>
          </html>';
}
?>
