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

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

$dept      = $_POST['dept'];
$leave_id = (int)$_POST['leave_id'];

$leaveTable = $dept.'_manager_leaves';
$msgTable   = $dept.'_manager_leave_messages';

/* ===============================
   FETCH LEAVE DETAILS
================================ */
$leaveStmt = $pdo->prepare("
    SELECT manager_id, leave_date, status 
    FROM $leaveTable 
    WHERE id=?
");
$leaveStmt->execute([$leave_id]);
$leave = $leaveStmt->fetch(PDO::FETCH_ASSOC);

if(!$leave) die('Invalid Leave');

/* ===============================
   SEND MESSAGE (HR → Manager)
================================ */
if(isset($_POST['send'])){
    $pdo->prepare("
        INSERT INTO $msgTable (leave_id, sender, message)
        VALUES (?, 'HR', ?)
    ")->execute([
        $leave_id,
        substr($_POST['message'],0,25)
    ]);
}

/* ===============================
   APPROVE LEAVE
================================ */
if(isset($_POST['approve'])){

    // 1️⃣ Update leave status
    $pdo->prepare("
        UPDATE $leaveTable 
        SET status='Approved' 
        WHERE id=?
    ")->execute([$leave_id]);

    // 2️⃣ Attendance table (manager1_attendance etc)
    $attendanceTable = 'manager'.$leave['manager_id'].'_attendance';

    // 3️⃣ Check attendance for that date
    $check = $pdo->prepare("
        SELECT id, status 
        FROM $attendanceTable 
        WHERE manager_id=? AND att_date=?
    ");
    $check->execute([
        $leave['manager_id'],
        $leave['leave_date']
    ]);

    if($check->rowCount() > 0){
        // 🔁 Attendance exists → UPDATE to Leave
        $pdo->prepare("
            UPDATE $attendanceTable 
            SET status='Leave' 
            WHERE manager_id=? AND att_date=?
        ")->execute([
            $leave['manager_id'],
            $leave['leave_date']
        ]);
    } else {
        // ➕ Attendance not exists → INSERT Leave
        $pdo->prepare("
            INSERT INTO $attendanceTable 
            (manager_id, att_date, status) 
            VALUES (?, ?, 'Leave')
        ")->execute([
            $leave['manager_id'],
            $leave['leave_date']
        ]);
    }
}

/* ===============================
   REJECT LEAVE
================================ */
if(isset($_POST['reject'])){
    $pdo->prepare("
        UPDATE $leaveTable 
        SET status='Rejected' 
        WHERE id=?
    ")->execute([$leave_id]);
}

header("Location: hr_manager_leaves.php");
exit;
