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

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

// Fetch the request
$request = $pdo->prepare("SELECT * FROM development_attendance_requests WHERE id=?");
$request->execute([$id]);
$req = $request->fetch();

if($req){
    $att_table = strtolower($req['department']).'_employee_attendance';
    $employee_id = $req['employee_id'];
    $att_date = $req['req_date'];

    if($action=='approve'){
        // Check if attendance already exists
        $check = $pdo->prepare("SELECT id FROM $att_table WHERE employee_id=? AND att_date=?");
        $check->execute([$employee_id, $att_date]);

        if($check->rowCount() > 0){
            // Update existing record to Present
            $pdo->prepare("UPDATE $att_table SET status='Present', marked_on=NOW() WHERE employee_id=? AND att_date=?")
                ->execute([$employee_id, $att_date]);
        } else {
            // Insert new record
            $pdo->prepare("INSERT INTO $att_table (employee_id, att_date, status, marked_on) VALUES (?,?, 'Present', NOW())")
                ->execute([$employee_id, $att_date]);
        }

        // Update request status
        $pdo->prepare("UPDATE development_attendance_requests SET status='Approved', marked_by=? WHERE id=?")
            ->execute([$_SESSION['hr_name'],$id]);

    } elseif($action=='reject'){
        $pdo->prepare("UPDATE development_attendance_requests SET status='Rejected', marked_by=? WHERE id=?")
            ->execute([$_SESSION['hr_name'],$id]);
    }
}

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