<?php
/**
 * Enterprise HRM ERP System - Attendance Approval/Rejection
 * Only Admin can approve/reject attendance
 */

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

// Load attendance isolation functions
require_once __DIR__ . '/../../includes/attendance_isolation.php';

// Only Admin can approve/reject
if (!canApproveAttendance()) {
    redirect(BASE_URL . '/dashboard.php', 'You do not have permission to approve/reject attendance.', 'error');
}

$attendanceId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$action = isset($_GET['action']) ? sanitize($_GET['action']) : ''; // approve, reject

if ($attendanceId <= 0 || !in_array($action, ['approve', 'reject'])) {
    redirect(BASE_URL . '/modules/attendance/list.php', 'Invalid request.', 'error');
}

try {
    $db = getDB();
    
    // Get attendance record
    $stmt = $db->prepare("
        SELECT a.*, e.employee_id, e.employee_code
        FROM attendance a
        INNER JOIN employees e ON a.employee_id = e.employee_id
        WHERE a.attendance_id = ?
    ");
    $stmt->execute([$attendanceId]);
    $attendance = $stmt->fetch();
    
    if (!$attendance) {
        redirect(BASE_URL . '/modules/attendance/list.php', 'Attendance record not found.', 'error');
    }
    
    // Validate access
    requireAttendanceAccess($attendance['employee_id']);
    
    // Update attendance status
    $status = $action === 'approve' ? 'approved' : 'rejected';
    $stmt = $db->prepare("
        UPDATE attendance 
        SET attendance_status = ?,
            updated_by = ?,
            updated_at = NOW()
        WHERE attendance_id = ?
    ");
    $stmt->execute([$status, getCurrentUserId(), $attendanceId]);
    
    logAudit('UPDATE', 'attendance', $attendanceId, "Attendance $action");
    
    redirect(BASE_URL . '/modules/attendance/list.php', "Attendance $action successfully.", 'success');
    
} catch (Exception $e) {
    error_log("Error approving/rejecting attendance: " . $e->getMessage());
    redirect(BASE_URL . '/modules/attendance/list.php', 'An error occurred. Please try again.', 'error');
}

