<?php
session_start();
require '../config/db.php';
if(!isset($_SESSION['hr_id'])) die('Unauthorized');

$id = $_POST['id'];
$hr_reason = $_POST['hr_reason'];

$request = $pdo->prepare("SELECT * FROM manager_attendance_requests WHERE id=?");
$request->execute([$id]);
$r = $request->fetch();

$manager_table = 'manager'.$r['manager_id'].'_attendance';

if(isset($_POST['approve'])){
    // Insert or update attendance
    $check = $pdo->prepare("SELECT * FROM $manager_table WHERE manager_id=? AND att_date=?");
    $check->execute([$r['manager_id'],$r['att_date']]);

    if($check->fetch()){
        $pdo->prepare("UPDATE $manager_table SET status=? WHERE manager_id=? AND att_date=?")
            ->execute([$r['requested_status'],$r['manager_id'],$r['att_date']]);
    } else {
        $pdo->prepare("INSERT INTO $manager_table (manager_id, att_date, status) VALUES (?,?,?)")
            ->execute([$r['manager_id'],$r['att_date'],$r['requested_status']]);
    }

    $pdo->prepare("
    UPDATE manager_attendance_requests 
    SET status='Approved', hr_reason=?, action_on=NOW()
    WHERE id=?
    ")->execute([$hr_reason,$id]);
}

if(isset($_POST['reject'])){
    $pdo->prepare("
    UPDATE manager_attendance_requests 
    SET status='Rejected', hr_reason=?, action_on=NOW()
    WHERE id=?
    ")->execute([$hr_reason,$id]);
}

header("Location: manager_attendance_requests.php");
