<?php
/**
 * Enterprise HRM ERP System - Mark Attendance
 */

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

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

$siteId = getCurrentSiteId();
$errors = [];
$formData = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'employee_id' => isset($_POST['employee_id']) ? (int)$_POST['employee_id'] : 0,
        'attendance_date' => $_POST['attendance_date'] ?? date('Y-m-d'),
        'check_in_time' => $_POST['check_in_time'] ?? '',
        'check_out_time' => $_POST['check_out_time'] ?? '',
        'attendance_status' => sanitize($_POST['attendance_status'] ?? 'present'),
        'remarks' => sanitize($_POST['remarks'] ?? ''),
    ];
    
    // Validation
    if (empty($formData['employee_id'])) {
        $errors[] = 'Please select an employee.';
    }
    
    if (empty($formData['attendance_date'])) {
        $errors[] = 'Attendance date is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $userId = getCurrentUserId();
            
            // Calculate total hours
            $totalHours = 0;
            $overtimeHours = 0;
            if (!empty($formData['check_in_time']) && !empty($formData['check_out_time'])) {
                $checkIn = new DateTime($formData['attendance_date'] . ' ' . $formData['check_in_time']);
                $checkOut = new DateTime($formData['attendance_date'] . ' ' . $formData['check_out_time']);
                $diff = $checkIn->diff($checkOut);
                $totalHours = $diff->h + ($diff->i / 60);
                
                $workingHours = getSetting('WORKING_HOURS_PER_DAY', 8);
                if ($totalHours > $workingHours) {
                    $overtimeHours = $totalHours - $workingHours;
                }
            }
            
            $sql = "
                INSERT INTO attendance (
                    site_id, employee_id, attendance_date, check_in_time, check_out_time,
                    total_hours, overtime_hours, attendance_status, remarks, created_by
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                    check_in_time = VALUES(check_in_time),
                    check_out_time = VALUES(check_out_time),
                    total_hours = VALUES(total_hours),
                    overtime_hours = VALUES(overtime_hours),
                    attendance_status = VALUES(attendance_status),
                    remarks = VALUES(remarks),
                    updated_by = VALUES(created_by),
                    updated_at = NOW()
            ";
            
            $checkIn = !empty($formData['check_in_time']) ? $formData['attendance_date'] . ' ' . $formData['check_in_time'] : null;
            $checkOut = !empty($formData['check_out_time']) ? $formData['attendance_date'] . ' ' . $formData['check_out_time'] : null;
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $siteId,
                $formData['employee_id'],
                $formData['attendance_date'],
                $checkIn,
                $checkOut,
                $totalHours,
                $overtimeHours,
                $formData['attendance_status'],
                $formData['remarks'] ?: null,
                $userId
            ]);
            
            redirect(BASE_URL . '/modules/attendance/list.php', 'Attendance marked successfully.');
            
        } catch (Exception $e) {
            error_log("Error marking attendance: " . $e->getMessage());
            $errors[] = 'An error occurred while marking attendance. Please try again.';
        }
    }
}

// Get employees
try {
    $db = getDB();
    $stmt = $db->prepare("
        SELECT employee_id, employee_code, 
               CONCAT(first_name, ' ', COALESCE(middle_name, ''), ' ', last_name) as full_name
        FROM employees 
        WHERE site_id = ? AND employment_status = 'active'
        ORDER BY employee_code
    ");
    $stmt->execute([$siteId]);
    $employees = $stmt->fetchAll();
} catch (Exception $e) {
    error_log("Error loading employees: " . $e->getMessage());
    $employees = [];
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Mark Attendance</h2>
        <a href="<?php echo BASE_URL; ?>/modules/attendance/list.php" class="btn btn-secondary">Back to List</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" id="attendanceForm">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label" for="employee_id">Employee *</label>
                <select id="employee_id" name="employee_id" class="form-control" required>
                    <option value="">Select Employee</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['employee_id']; ?>" 
                            <?php echo ($formData['employee_id'] ?? 0) == $emp['employee_id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($emp['employee_code'] . ' - ' . $emp['full_name']); ?>
                    </option>
                    <?php endforeach; ?>
                </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="check_in_time">Check In Time</label>
                <input type="time" id="check_in_time" name="check_in_time" class="form-control"
                       value="<?php echo htmlspecialchars($formData['check_in_time'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="check_out_time">Check Out Time</label>
                <input type="time" id="check_out_time" name="check_out_time" class="form-control"
                       value="<?php echo htmlspecialchars($formData['check_out_time'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="attendance_status">Status *</label>
                <select id="attendance_status" name="attendance_status" class="form-control" required>
                    <option value="present" <?php echo ($formData['attendance_status'] ?? 'present') === 'present' ? 'selected' : ''; ?>>Present</option>
                    <option value="absent" <?php echo ($formData['attendance_status'] ?? '') === 'absent' ? 'selected' : ''; ?>>Absent</option>
                    <option value="late" <?php echo ($formData['attendance_status'] ?? '') === 'late' ? 'selected' : ''; ?>>Late</option>
                    <option value="half_day" <?php echo ($formData['attendance_status'] ?? '') === 'half_day' ? 'selected' : ''; ?>>Half Day</option>
                    <option value="on_leave" <?php echo ($formData['attendance_status'] ?? '') === 'on_leave' ? 'selected' : ''; ?>>On Leave</option>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="remarks">Remarks</label>
                <textarea id="remarks" name="remarks" class="form-control" rows="3"><?php echo htmlspecialchars($formData['remarks'] ?? ''); ?></textarea>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right;">
            <a href="<?php echo BASE_URL; ?>/modules/attendance/list.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Mark Attendance</button>
        </div>
    </form>
</div>

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

