<?php
session_start();

if (!isset($_SESSION['manager_id'])) die('Unauthorized');
if ($_SESSION['department'] !== 'Sales') {
    header('Location: login.php');
    exit;
}

require 'config/db.php';

$dept  = 'Sales';
$table = strtolower($dept).'_employee_entry_times';

$msg = '';
$type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $employee_id = (int)$_POST['employee_id'];
    $entry_date  = $_POST['entry_date'];
    $entry_time  = $_POST['entry_time'];

    // 🔍 Duplicate check (employee + date)
    $check = $pdo->prepare("
        SELECT id FROM $table
        WHERE employee_id=? AND entry_date=?
    ");
    $check->execute([$employee_id, $entry_date]);

    if ($check->rowCount() > 0) {

        $msg  = "Entry time already set for this employee on selected date.";
        $type = "danger";

    } else {

        $pdo->prepare("
            INSERT INTO $table
            (department, employee_id, entry_date, entry_time, created_by_manager)
            VALUES (?,?,?,?,?)
        ")->execute([
            $dept,
            $employee_id,
            $entry_date,
            $entry_time,
            $_SESSION['manager_id']
        ]);

        $msg  = "Entry time set successfully for selected date.";
        $type = "success";
    }
}

/* ===== PAGE TITLE ===== */
$page_title = "Sales Manager • Set Employee Entry Time";

/* ===== LAYOUT START ===== */
include 'assets/layout_top.php';
?>
<br><br>
<div class="glass-panel p-4 mx-auto" style="max-width:550px;">

<h3 class="mb-4 text-center">
    <i class="fa-solid fa-clock me-2"></i>Set Employee Entry Time
</h3>

<?php if($msg): ?>
<div class="alert alert-<?= $type ?>"><?= htmlspecialchars($msg) ?></div>
<?php endif; ?>

<div class="glass-card p-3 shadow-sm">

<form method="POST" id="entryForm">

<div class="mb-3">
<label class="form-label">Employee</label>
<select name="employee_id" class="form-select" required>
<option value="">-- Select Employee --</option>
<?php
$emps = $pdo->query("SELECT id, full_name FROM sales_employees ORDER BY full_name");
foreach($emps as $e){
    echo "<option value='{$e['id']}'>{$e['full_name']}</option>";
}
?>
</select>
</div>

<div class="mb-3">
<label class="form-label">Entry Date</label>
<input type="date" name="entry_date" class="form-control" required>
</div>

<div class="mb-3">
<label class="form-label">Entry Time</label>
<input type="time" name="entry_time" class="form-control" required>
</div>

<button class="btn-main w-100"><i class="fa-solid fa-check me-1"></i> Set Entry Time</button>

</form>

</div>
</div>

<script>
// prevent Enter auto-submit
document.getElementById('entryForm').addEventListener('keydown', e=>{
    if(e.key === 'Enter') e.preventDefault();
});
</script>

<?php
/* ===== LAYOUT END ===== */
include 'assets/layout_bottom.php';
?>
