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

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

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

$siteId = getCurrentSiteId();
$attendanceId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($attendanceId <= 0) {
    redirect(BASE_URL . '/modules/attendance/list.php', 'Invalid attendance ID.', 'error');
}

// Get attendance record
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM attendance WHERE attendance_id = ? AND site_id = ?");
    $stmt->execute([$attendanceId, $siteId]);
    $record = $stmt->fetch();
    
    if (!$record) {
        redirect(BASE_URL . '/modules/attendance/list.php', 'Attendance record not found.', 'error');
    }
    
    $formData = $record;
    
} catch (Exception $e) {
    error_log("Error loading attendance: " . $e->getMessage());
    redirect(BASE_URL . '/modules/attendance/list.php', 'Error loading attendance data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'attendance_date' => $_POST['attendance_date'] ?? '',
        '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'] ?? ''),
    ];
    
    if (empty($formData['attendance_date'])) {
        $errors[] = 'Attendance date is required.';
    }
    
    if (empty($errors)) {
        try {
            $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;
                }
            }
            
            $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;
            
            $sql = "
                UPDATE attendance SET
                    attendance_date = ?,
                    check_in_time = ?,
                    check_out_time = ?,
                    total_hours = ?,
                    overtime_hours = ?,
                    attendance_status = ?,
                    remarks = ?,
                    updated_by = ?,
                    updated_at = NOW()
                WHERE attendance_id = ? AND site_id = ?
            ";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $formData['attendance_date'],
                $checkIn,
                $checkOut,
                $totalHours,
                $overtimeHours,
                $formData['attendance_status'],
                $formData['remarks'] ?: null,
                $userId,
                $attendanceId,
                $siteId
            ]);
            
            redirect(BASE_URL . '/modules/attendance/list.php', 'Attendance updated successfully.');
            
        } catch (Exception $e) {
            error_log("Error updating attendance: " . $e->getMessage());
            $errors[] = 'An error occurred while updating attendance. Please try again.';
        }
    }
}

// Extract time from datetime
$checkInTime = '';
$checkOutTime = '';
if (!empty($formData['check_in_time'])) {
    $dt = new DateTime($formData['check_in_time']);
    $checkInTime = $dt->format('H:i');
}
if (!empty($formData['check_out_time'])) {
    $dt = new DateTime($formData['check_out_time']);
    $checkOutTime = $dt->format('H:i');
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit 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="attendance_date">Date *</label>
                <input type="date" id="attendance_date" name="attendance_date" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['attendance_date']); ?>">
            </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($checkInTime); ?>">
            </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($checkOutTime); ?>">
            </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">Update Attendance</button>
        </div>
    </form>
</div>

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

