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

if(!isset($_SESSION['manager_id'])) die('Unauthorized');

$dept = $_SESSION['department'];
$msgTable = $dept.'_manager_leave_messages';
$leaveTable = $dept.'_manager_leaves';

// Check leave status
$check = $pdo->prepare("SELECT status FROM $leaveTable WHERE id=?");
$check->execute([$_POST['leave_id']]);
$status = $check->fetchColumn();

if($status !== 'Pending'){
    die('Messaging closed');
}

// Insert message
$pdo->prepare("
INSERT INTO $msgTable (leave_id,sender,message)
VALUES (?,?,?)
")->execute([
    $_POST['leave_id'],
    'Manager',
    substr($_POST['message'],0,25)
]);

header("Location: my_leaves.php");
