<?php
/**
 * Enterprise HRM ERP System - Attendance Form
 * Check In / Check Out form for employees
 */

require_once __DIR__ . '/../../includes/init.php';
requireLogin();
requirePermission('ATTENDANCE_CREATE');

$pageTitle = 'Attendance Form';
$currentModule = 'attendance';

$errors = [];
$success = false;
$formData = [];

// Pre-fill from URL parameters
$formData['employee_id'] = isset($_GET['employee_id']) ? (int)$_GET['employee_id'] : 0;
$formData['attendance_date'] = isset($_GET['date']) ? sanitize($_GET['date']) : date('Y-m-d');
$formData['punch_time'] = date('H:i');

$siteId = getCurrentSiteId();

// Super Admin doesn't need site selection (can check in employees from any site)
// HR Admin and Employee need site selection
if (!isSuperAdmin() && !$siteId) {
    redirect(BASE_URL . '/dashboard.php', 'Please select a site first.', 'error');
}

// Get employees for dropdown
// If employee role, show only their own record
try {
    $db = getDB();
    require_once __DIR__ . '/../../includes/data_isolation.php';
    
    if (isEmployee()) {
        // Employee can only see their own record
        $stmt = $db->prepare("
            SELECT employee_id, employee_code, first_name, middle_name, last_name, employment_status
            FROM employees 
            WHERE email = ? AND employment_status = 'active'
            LIMIT 1
        ");
        $stmt->execute([$_SESSION['email'] ?? '']);
        $employees = $stmt->fetchAll();
        
        // Auto-select employee if found
        if (!empty($employees) && empty($formData['employee_id'])) {
            $formData['employee_id'] = $employees[0]['employee_id'];
        }
    } else {
        // Super Admin and HR Admin can see all employees in their accessible sites
        $accessibleSiteIds = getAccessibleSiteIds();
        
        if (empty($accessibleSiteIds)) {
            $employees = [];
        } else {
            $placeholders = implode(',', array_fill(0, count($accessibleSiteIds), '?'));
            
            // Super Admin can see all employees across all sites
            // HR Admin can see employees in their assigned sites
            $stmt = $db->prepare("
                SELECT employee_id, employee_code, first_name, middle_name, last_name, employment_status, site_id
                FROM employees 
                WHERE employment_status = 'active' AND site_id IN ($placeholders)
                ORDER BY site_id, employee_code, first_name, last_name
            ");
            $stmt->execute($accessibleSiteIds);
            $employees = $stmt->fetchAll();
        }
    }
} catch (Exception $e) {
    error_log("Error loading employees: " . $e->getMessage());
    $employees = [];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'employee_id' => isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0,
        'attendance_date' => sanitize($_POST['attendance_date'] ?? date('Y-m-d')),
        'mode' => sanitize($_POST['mode'] ?? 'check_in'),
        'punch_time' => sanitize($_POST['punch_time'] ?? ''),
        'out_time' => sanitize($_POST['out_time'] ?? ''),
    ];
    
    // Validation
    if ($formData['employee_id'] <= 0) {
        $errors[] = 'Please select an employee.';
    }
    
    if (empty($formData['attendance_date'])) {
        $errors[] = 'Date is required.';
    }
    
    if (empty($formData['punch_time'])) {
        $errors[] = 'Punch time is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $db->beginTransaction();
            
            // Get employee's site_id (Super Admin can check in employees from any site)
            $stmt = $db->prepare("SELECT site_id FROM employees WHERE employee_id = ?");
            $stmt->execute([$formData['employee_id']]);
            $employeeData = $stmt->fetch();
            $employeeSiteId = $employeeData ? $employeeData['site_id'] : $siteId;
            
            // For Super Admin, use employee's site_id; for others, use current site_id
            $attendanceSiteId = (isSuperAdmin() && $employeeSiteId) ? $employeeSiteId : $siteId;
            
            // Verify employee belongs to accessible site
            if (!isSuperAdmin() && !isHRAdmin()) {
                // Employee can only check in themselves
                if (isEmployee()) {
                    $stmt = $db->prepare("SELECT employee_id FROM employees WHERE employee_id = ? AND email = ?");
                    $stmt->execute([$formData['employee_id'], $_SESSION['email'] ?? '']);
                    if (!$stmt->fetch()) {
                        $errors[] = 'You can only check in yourself.';
                        $db->rollBack();
                    }
                }
            } else {
                // HR Admin/Super Admin - verify employee is in accessible site
                $accessibleSiteIds = getAccessibleSiteIds();
                if (!in_array($employeeSiteId, $accessibleSiteIds)) {
                    $errors[] = 'You do not have access to check in this employee.';
                    $db->rollBack();
                }
            }
            
            if (empty($errors)) {
                // Check if attendance record exists for this date
                $stmt = $db->prepare("
                    SELECT attendance_id, check_in_time, check_out_time 
                    FROM attendance 
                    WHERE employee_id = ? AND attendance_date = ? AND site_id = ?
                ");
                $stmt->execute([$formData['employee_id'], $formData['attendance_date'], $attendanceSiteId]);
                $existing = $stmt->fetch();
                
                $punchDateTime = $formData['attendance_date'] . ' ' . $formData['punch_time'];
                
                $outDateTime = !empty($formData['out_time']) ? $formData['attendance_date'] . ' ' . $formData['out_time'] : null;
                
                if ($existing) {
                // Update existing record
                if ($formData['mode'] === 'check_in') {
                    $updateSql = "
                        UPDATE attendance SET
                            check_in_time = ?,
                            attendance_status = 'present',
                            updated_by = ?,
                            updated_at = NOW()
                    ";
                    $updateParams = [$punchDateTime, getCurrentUserId(), $existing['attendance_id']];
                    
                    // If out time is provided, update it too
                    if ($outDateTime) {
                        $updateSql = "
                            UPDATE attendance SET
                                check_in_time = ?,
                                check_out_time = ?,
                                attendance_status = 'present',
                                updated_by = ?,
                                updated_at = NOW()
                        ";
                        $updateParams = [$punchDateTime, $outDateTime, getCurrentUserId(), $existing['attendance_id']];
                        
                        // Calculate total hours
                        $checkIn = new DateTime($punchDateTime);
                        $checkOut = new DateTime($outDateTime);
                        $diff = $checkIn->diff($checkOut);
                        $totalHours = $diff->h + ($diff->i / 60) + ($diff->s / 3600);
                        
                        $updateSql .= ", total_hours = ?";
                        $updateParams[] = $totalHours;
                    }
                    
                    $updateSql .= " WHERE attendance_id = ?";
                    $updateParams[] = $existing['attendance_id'];
                    
                    $stmt = $db->prepare($updateSql);
                    $stmt->execute($updateParams);
                } else {
                    // Check out
                    if (empty($existing['check_in_time'])) {
                        $errors[] = 'Cannot check out without check-in. Please check in first.';
                        $db->rollBack();
                    } else {
                        $stmt = $db->prepare("
                            UPDATE attendance SET
                                check_out_time = ?,
                                updated_by = ?,
                                updated_at = NOW()
                            WHERE attendance_id = ?
                        ");
                        $stmt->execute([$punchDateTime, getCurrentUserId(), $existing['attendance_id']]);
                        
                        // Calculate total hours
                        $checkIn = new DateTime($existing['check_in_time']);
                        $checkOut = new DateTime($punchDateTime);
                        $diff = $checkIn->diff($checkOut);
                        $totalHours = $diff->h + ($diff->i / 60) + ($diff->s / 3600);
                        
                        $stmt = $db->prepare("
                            UPDATE attendance SET
                                total_hours = ?
                            WHERE attendance_id = ?
                        ");
                        $stmt->execute([$totalHours, $existing['attendance_id']]);
                    }
                }
            } else {
                // Create new record
                if ($formData['mode'] === 'check_in') {
                    $insertSql = "
                        INSERT INTO attendance (
                            site_id, employee_id, attendance_date, check_in_time, 
                            attendance_status, created_by, updated_by
                    ";
                    $insertValues = "VALUES (?, ?, ?, ?, 'present', ?, ?)";
                    $insertParams = [
                        $attendanceSiteId,
                        $formData['employee_id'],
                        $formData['attendance_date'],
                        $punchDateTime,
                        getCurrentUserId(),
                        getCurrentUserId()
                    ];
                    
                    // If out time is provided, include it
                    if ($outDateTime) {
                        $insertSql .= ", check_out_time, total_hours";
                        $insertValues = "VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                        
                        // Calculate total hours
                        $checkIn = new DateTime($punchDateTime);
                        $checkOut = new DateTime($outDateTime);
                        $diff = $checkIn->diff($checkOut);
                        $totalHours = $diff->h + ($diff->i / 60) + ($diff->s / 3600);
                        
                        $insertParams = [
                            $attendanceSiteId,
                            $formData['employee_id'],
                            $formData['attendance_date'],
                            $punchDateTime,
                            $outDateTime,
                            $totalHours,
                            getCurrentUserId(),
                            getCurrentUserId()
                        ];
                    }
                    
                    $insertSql .= ") " . $insertValues;
                    $stmt = $db->prepare($insertSql);
                    $stmt->execute($insertParams);
                } else {
                    $errors[] = 'Cannot check out without check-in. Please check in first.';
                    $db->rollBack();
                }
            }
            
                if (empty($errors)) {
                    $db->commit();
                    $success = true;
                    $attendanceId = $db->lastInsertId() ?: ($existing['attendance_id'] ?? 0);
                    
                    // Log audit trail
                    if (function_exists('logAudit')) {
                        logAudit('CREATE', 'attendance', $attendanceId, 'Attendance ' . ($formData['mode'] === 'check_in' ? 'Check In' : 'Check Out') . ' recorded');
                    }
                    
                    // Get employee name for success message
                    $stmt = $db->prepare("SELECT first_name, middle_name, last_name, employee_code FROM employees WHERE employee_id = ?");
                    $stmt->execute([$formData['employee_id']]);
                    $empData = $stmt->fetch();
                    
                    // Keep employee and date for convenience, but reset time
                    $formData['punch_time'] = date('H:i');
                    $formData['out_time'] = '';
                    // Don't reset employee_id and date - keep them for next entry
                    
                    // Store employee name in formData for success message
                    if ($empData) {
                        $formData['employee_name'] = trim($empData['first_name'] . ' ' . ($empData['middle_name'] ?? '') . ' ' . $empData['last_name']);
                        $formData['employee_code'] = $empData['employee_code'];
                    }
                }
            }
            
        } catch (Exception $e) {
            if ($db->inTransaction()) {
                $db->rollBack();
            }
            error_log("Error saving attendance: " . $e->getMessage());
            $errors[] = 'An error occurred while saving attendance. Please try again.';
        }
    }
}

include __DIR__ . '/../../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Attendance Form</h2>
        <div style="display: flex; gap: 10px;">
            <?php if (hasPermission('ATTENDANCE_CREATE')): ?>
            <a href="<?php echo BASE_URL; ?>/modules/attendance/bulk_checkin.php" class="btn" style="background: #28a745; color: white;">Bulk Check In</a>
            <?php endif; ?>
            <a href="<?php echo BASE_URL; ?>/modules/attendance/index.php" class="btn btn-secondary">All Features</a>
            <a href="<?php echo BASE_URL; ?>/modules/attendance/list.php" class="btn btn-secondary">Back to Attendance</a>
        </div>
    </div>
    
    <?php if ($success): ?>
    <div id="successMessage" class="success-toast" style="margin-top: 20px; padding: 20px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border-radius: 12px; border: none; box-shadow: 0 8px 24px rgba(16, 185, 129, 0.3); animation: slideDown 0.5s ease-out;">
        <div style="display: flex; align-items: center; gap: 12px;">
            <div style="font-size: 32px; line-height: 1;">✅</div>
            <div style="flex: 1;">
                <div style="font-size: 18px; font-weight: 700; margin-bottom: 4px;">Success!</div>
                <div style="font-size: 14px; opacity: 0.95;">
                    Attendance <?php echo htmlspecialchars($formData['mode'] === 'check_in' ? 'Check In' : 'Check Out'); ?> recorded successfully!
                    <?php 
                    if (isset($formData['employee_name'])) {
                        echo ' for <strong>' . htmlspecialchars($formData['employee_code'] . ' - ' . $formData['employee_name']) . '</strong>';
                    }
                    if (isset($formData['attendance_date'])) {
                        echo ' on <strong>' . date('d M Y', strtotime($formData['attendance_date'])) . '</strong>';
                    }
                    ?>
                </div>
            </div>
            <button onclick="document.getElementById('successMessage').style.display='none'" style="background: rgba(255,255,255,0.2); border: none; color: white; font-size: 20px; cursor: pointer; padding: 4px 12px; border-radius: 6px; transition: background 0.2s;" onmouseover="this.style.background='rgba(255,255,255,0.3)'" onmouseout="this.style.background='rgba(255,255,255,0.2)'">×</button>
        </div>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error" style="margin-top: 20px; padding: 20px; background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%); color: #991b1b; border-radius: 12px; border: 2px solid #ef4444; box-shadow: 0 4px 12px rgba(239, 68, 68, 0.2);">
        <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
            <div style="font-size: 24px;">❌</div>
            <div style="font-weight: 700; font-size: 16px;">Please fix the following errors:</div>
        </div>
        <ul style="margin: 0; padding-left: 20px; list-style: none;">
            <?php foreach ($errors as $error): ?>
            <li style="margin-bottom: 8px; padding-left: 8px; position: relative;">
                <span style="position: absolute; left: -12px;">•</span>
                <?php echo htmlspecialchars($error); ?>
            </li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" id="attendanceForm" style="margin-top: 20px;" onsubmit="return validateForm()">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <!-- Mode Selection -->
            <div style="grid-column: 1 / -1; display: flex; gap: 12px; margin-bottom: 24px; background: #f8fafc; padding: 8px; border-radius: 12px;">
                <button type="button" id="checkInBtn" class="mode-btn" data-mode="check_in" style="flex: 1; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 14px 20px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 15px; transition: all 0.3s; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);">
                    ✓ Check In
                </button>
                <button type="button" id="checkOutBtn" class="mode-btn" data-mode="check_out" style="flex: 1; background: #6c757d; color: white; padding: 14px 20px; border: none; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 15px; transition: all 0.3s;">
                    ✓ Check Out
                </button>
            </div>
            <input type="hidden" name="mode" id="mode" value="<?php echo htmlspecialchars($formData['mode'] ?? 'check_in'); ?>">
            
            <div class="form-group">
                <label class="form-label" for="employee_id">Employee Name *</label>
                <?php if (isEmployee() && count($employees) == 1): ?>
                <!-- Employee role - show as read-only -->
                <input type="hidden" name="employee_id" value="<?php echo $employees[0]['employee_id']; ?>">
                <input type="text" class="form-control" 
                       value="<?php echo htmlspecialchars($employees[0]['employee_code'] . ' - ' . trim($employees[0]['first_name'] . ' ' . ($employees[0]['middle_name'] ?? '') . ' ' . $employees[0]['last_name'])); ?>" 
                       readonly style="background: #f3f4f6;">
                <?php else: ?>
                <select id="employee_id" name="employee_id" class="form-control" required>
                    <option value="">Select Employee</option>
                    <?php foreach ($employees as $emp): 
                        $empName = trim($emp['first_name'] . ' ' . ($emp['middle_name'] ?? '') . ' ' . $emp['last_name']);
                    ?>
                    <option value="<?php echo $emp['employee_id']; ?>" 
                            <?php echo ($formData['employee_id'] ?? 0) == $emp['employee_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($emp['employee_code'] . ' - ' . $empName); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
                <?php endif; ?>
                <?php if (!isEmployee()): ?>
                <small style="color: #64748b; font-size: 12px; margin-top: 6px; display: block; padding: 8px 12px; background: #f0f9ff; border-left: 3px solid #3b82f6; border-radius: 4px;">
                    <?php if (isSuperAdmin()): ?>
                        <strong>👑 Super Admin:</strong> You can check in any employee from any site. Select the employee from the dropdown above.
                    <?php elseif (isHRAdmin()): ?>
                        <strong>👤 HR Admin:</strong> You can check in employees from your assigned site(s). Select the employee from the dropdown above.
                    <?php else: ?>
                        <strong>💡 Admin Access:</strong> You can check in employees. Select the employee from the dropdown above.
                    <?php endif; ?>
                </small>
                <?php endif; ?>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="year">Year *</label>
                <select id="year" name="year" class="form-control" required onchange="updateDate()">
                    <?php 
                    $currentYear = date('Y');
                    for ($y = $currentYear; $y >= $currentYear - 2; $y--): 
                        $selected = isset($formData['attendance_date']) ? date('Y', strtotime($formData['attendance_date'])) == $y : $currentYear == $y;
                    ?>
                    <option value="<?php echo $y; ?>" <?php echo $selected ? 'selected' : ''; ?>>
                        <?php echo $y; ?>
                    </option>
                    <?php endfor; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="month">Month *</label>
                <select id="month" name="month" class="form-control" required onchange="updateDate()">
                    <?php 
                    $months = ['January', 'February', 'March', 'April', 'May', 'June', 
                              'July', 'August', 'September', 'October', 'November', 'December'];
                    $currentMonth = isset($formData['attendance_date']) ? date('m', strtotime($formData['attendance_date'])) : date('m');
                    for ($m = 1; $m <= 12; $m++): 
                        $selected = $currentMonth == $m;
                    ?>
                    <option value="<?php echo $m; ?>" <?php echo $selected ? 'selected' : ''; ?>>
                        <?php echo $months[$m - 1]; ?>
                    </option>
                    <?php endfor; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="attendance_date">Date *</label>
                <input type="date" id="attendance_date" name="attendance_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['attendance_date'] ?? date('Y-m-d')); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="punch_time">In Time *</label>
                <input type="time" id="punch_time" name="punch_time" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['punch_time'] ?? date('H:i')); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="out_time">Out Time</label>
                <input type="time" id="out_time" name="out_time" class="form-control"
                       value="<?php echo htmlspecialchars($formData['out_time'] ?? ''); ?>">
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <button type="submit" id="submitBtn" class="btn btn-primary" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 14px 36px; font-size: 16px; font-weight: 600; cursor: pointer; border: none; border-radius: 8px; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3); transition: all 0.2s;">
                <span id="submitText">✓ Check In</span>
            </button>
        </div>
    </form>
</div>

<style>
@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes pulse {
    0%, 100% {
        transform: scale(1);
    }
    50% {
        transform: scale(1.05);
    }
}

.success-toast {
    animation: slideDown 0.5s ease-out;
}

.btn-loading {
    position: relative;
    pointer-events: none;
    opacity: 0.7;
}

.btn-loading::after {
    content: '';
    position: absolute;
    width: 16px;
    height: 16px;
    top: 50%;
    left: 50%;
    margin-left: -8px;
    margin-top: -8px;
    border: 2px solid rgba(255,255,255,0.3);
    border-top-color: white;
    border-radius: 50%;
    animation: spin 0.6s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.form-group.required label::after {
    content: ' *';
    color: #ef4444;
    font-weight: bold;
}
</style>

<script>
// Make setMode globally available
window.setMode = function(mode) {
    console.log('Setting mode to:', mode);
    
    // Update hidden input
    var modeInput = document.getElementById('mode');
    if (modeInput) {
        modeInput.value = mode;
    }
    
    var checkInBtn = document.getElementById('checkInBtn');
    var checkOutBtn = document.getElementById('checkOutBtn');
    var submitBtn = document.getElementById('submitBtn');
    var submitText = document.getElementById('submitText');
    
    if (mode === 'check_in') {
        // Check In Active - Green
        if (checkInBtn) {
            checkInBtn.style.background = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
            checkInBtn.style.fontWeight = '600';
            checkInBtn.style.boxShadow = '0 4px 12px rgba(16, 185, 129, 0.3)';
            checkInBtn.style.transform = 'scale(1.02)';
        }
        
        if (checkOutBtn) {
            checkOutBtn.style.background = '#6c757d';
            checkOutBtn.style.fontWeight = '500';
            checkOutBtn.style.boxShadow = 'none';
            checkOutBtn.style.transform = 'scale(1)';
        }
        
        if (submitText) submitText.innerHTML = '✓ Check In';
        if (submitBtn) {
            submitBtn.style.background = 'linear-gradient(135deg, #10b981 0%, #059669 100%)';
            submitBtn.style.boxShadow = '0 4px 12px rgba(16, 185, 129, 0.3)';
        }
    } else {
        // Check Out Active - Red
        if (checkInBtn) {
            checkInBtn.style.background = '#6c757d';
            checkInBtn.style.fontWeight = '500';
            checkInBtn.style.boxShadow = 'none';
            checkInBtn.style.transform = 'scale(1)';
        }
        
        if (checkOutBtn) {
            checkOutBtn.style.background = 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)';
            checkOutBtn.style.fontWeight = '600';
            checkOutBtn.style.boxShadow = '0 4px 12px rgba(239, 68, 68, 0.3)';
            checkOutBtn.style.transform = 'scale(1.02)';
        }
        
        if (submitText) submitText.innerHTML = '✓ Check Out';
        if (submitBtn) {
            submitBtn.style.background = 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)';
            submitBtn.style.boxShadow = '0 4px 12px rgba(239, 68, 68, 0.3)';
        }
    }
};

function updateDate() {
    const year = document.getElementById('year').value;
    const month = document.getElementById('month').value;
    const day = document.getElementById('attendance_date').value ? new Date(document.getElementById('attendance_date').value).getDate() : new Date().getDate();
    
    // Get last day of month
    const lastDay = new Date(year, month, 0).getDate();
    const selectedDay = Math.min(day, lastDay);
    
    const dateStr = year + '-' + String(month).padStart(2, '0') + '-' + String(selectedDay).padStart(2, '0');
    document.getElementById('attendance_date').value = dateStr;
}

function validateForm() {
    var employeeId = document.getElementById('employee_id');
    if (!employeeId) {
        employeeId = document.querySelector('input[name="employee_id"]');
    }
    employeeId = employeeId ? employeeId.value : '';
    
    var date = document.getElementById('attendance_date').value;
    var time = document.getElementById('punch_time').value;
    var modeInput = document.getElementById('mode');
    var mode = modeInput ? modeInput.value : 'check_in';
    
    // Ensure mode is set
    if (!mode || (mode !== 'check_in' && mode !== 'check_out')) {
        alert('Please select Check In or Check Out mode.');
        return false;
    }
    
    var errors = [];
    
    if (!employeeId || employeeId === '' || employeeId === '0') {
        errors.push('Please select an employee.');
        if (document.getElementById('employee_id')) {
            document.getElementById('employee_id').focus();
        }
    }
    
    if (!date) {
        errors.push('Please select a date.');
        if (errors.length === 1) {
            document.getElementById('attendance_date').focus();
        }
    }
    
    if (!time) {
        errors.push('Please select a punch time.');
        if (errors.length === 1) {
            document.getElementById('punch_time').focus();
        }
    }
    
    if (errors.length > 0) {
        alert(errors.join('\n'));
        return false;
    }
    
    // Show loading state
    var submitBtn = document.getElementById('submitBtn');
    var submitText = document.getElementById('submitText');
    if (submitBtn) {
        submitBtn.disabled = true;
        submitBtn.classList.add('btn-loading');
    }
    if (submitText) {
        submitText.innerHTML = mode === 'check_in' ? 'Processing Check In...' : 'Processing Check Out...';
    }
    
    // Scroll to top to see success message
    window.scrollTo({ top: 0, behavior: 'smooth' });
    
    // Allow form submission
    return true;
}

function showToast(message, type = 'success') {
    const toast = document.createElement('div');
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 16px 24px;
        background: ${type === 'error' ? 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)' : 'linear-gradient(135deg, #10b981 0%, #059669 100%)'};
        color: white;
        border-radius: 12px;
        box-shadow: 0 8px 24px rgba(0,0,0,0.2);
        z-index: 10000;
        animation: slideDown 0.3s ease-out;
        max-width: 400px;
        font-weight: 500;
    `;
    toast.innerHTML = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.style.animation = 'slideDown 0.3s ease-out reverse';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    console.log('Form initialized');
    
    // Get mode from hidden input
    var modeInput = document.getElementById('mode');
    var currentMode = modeInput ? modeInput.value : 'check_in';
    
    // Set initial mode
    window.setMode(currentMode);
    
    // Setup button click handlers
    var checkInBtn = document.getElementById('checkInBtn');
    var checkOutBtn = document.getElementById('checkOutBtn');
    
    if (checkInBtn) {
        checkInBtn.onclick = function() {
            console.log('Check In button clicked');
            window.setMode('check_in');
        };
    }
    
    if (checkOutBtn) {
        checkOutBtn.onclick = function() {
            console.log('Check Out button clicked');
            window.setMode('check_out');
        };
    }
    
    console.log('Button handlers attached');
});

// Auto-scroll to top on success to show message
<?php if ($success): ?>
window.scrollTo({ top: 0, behavior: 'smooth' });
// Auto-hide success message after 5 seconds
setTimeout(function() {
    const successMsg = document.getElementById('successMessage');
    if (successMsg) {
        successMsg.style.animation = 'slideDown 0.3s ease-out reverse';
        setTimeout(() => successMsg.style.display = 'none', 300);
    }
}, 5000);
<?php endif; ?>

// Re-enable submit button if form validation fails (browser validation)
document.getElementById('attendanceForm').addEventListener('invalid', function(e) {
    const submitBtn = document.getElementById('submitBtn');
    const submitText = document.getElementById('submitText');
    submitBtn.disabled = false;
    submitBtn.classList.remove('btn-loading');
    const mode = document.getElementById('mode').value;
    submitText.innerHTML = mode === 'check_in' ? '✓ Check In' : '✓ Check Out';
}, true);

// Reset button state if form is reset
document.getElementById('attendanceForm').addEventListener('reset', function() {
    const submitBtn = document.getElementById('submitBtn');
    const submitText = document.getElementById('submitText');
    submitBtn.disabled = false;
    submitBtn.classList.remove('btn-loading');
    const mode = document.getElementById('mode').value;
    submitText.innerHTML = mode === 'check_in' ? '✓ Check In' : '✓ Check Out';
});
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>

