<?php
session_start();
require 'config/db.php';

if (!isset($_SESSION['employee_id'])) {
    die('Unauthorized access');
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die('Invalid request');
}

$emp_id = $_SESSION['employee_id'];
$reply  = trim($_POST['reply'] ?? '');
$leave_id = intval($_POST['id'] ?? 0);

if ($leave_id <= 0 || $reply === '') {
    die('Invalid data');
}

/*
 SECURITY CHECK:
 Ensure this leave belongs to this employee
 and manager has actually asked a question
*/
$check = $pdo->prepare("
    SELECT id 
    FROM employee_leave_requests 
    WHERE id = ? 
      AND employee_id = ?
      AND manager_quote IS NOT NULL
      AND employee_reply IS NULL
");
$check->execute([$leave_id, $emp_id]);

if (!$check->fetch()) {
    die('Action not allowed');
}

/* Update employee reply */
$update = $pdo->prepare("
    UPDATE employee_leave_requests 
    SET employee_reply = ?, replied_at = NOW()
    WHERE id = ?
");
$update->execute([$reply, $leave_id]);

/* Optional: Flash message */
$_SESSION['success'] = 'Reply sent to manager successfully';

/* Redirect back */
header('Location: dashboard.php');
exit;
