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

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

$emp_id = $_SESSION['employee_id'];
$dept = $_SESSION['department'];
$today = date('Y-m-d');

// Determine employee attendance table based on department
$attendance_table = strtolower($dept) . '_employee_attendance';

// Check if attendance already marked
$stmt = $pdo->prepare("SELECT * FROM $attendance_table WHERE employee_id=? AND att_date=?");
$stmt->execute([$emp_id, $today]);
$existing = $stmt->fetch();

if ($existing) {
    // Already marked
    $_SESSION['attendance_msg'] = "Today's attendance is already marked!";
    header("Location: dashboard.php");
    exit;
}

// Insert today's attendance as Present
$stmt = $pdo->prepare("INSERT INTO $attendance_table (employee_id, att_date, status) VALUES (?,?,?)");
$stmt->execute([$emp_id, $today, 'Present']);

// Success message
$_SESSION['attendance_msg'] = "Attendance marked successfully!";
header("Location: dashboard.php");
exit;
