<?php
// admin/get-salary-deduction.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    exit;
}

$employee_id = intval($_GET['employee_id'] ?? 0);
$month = $_GET['month'] ?? date('Y-m');

if ($employee_id > 0 && !empty($month)) {
    try {
        // Get employee daily salary
        $stmt = $pdo->prepare("SELECT base_salary FROM employees WHERE id = ?");
        $stmt->execute([$employee_id]);
        $employee = $stmt->fetch();
        
        if (!$employee) {
            echo json_encode(['error' => 'Employee not found']);
            exit;
        }
        
        // Get total days in month
        $year = substr($month, 0, 4);
        $month_num = substr($month, 5, 2);
        $total_days = cal_days_in_month(CAL_GREGORIAN, $month_num, $year);
        
        // Count working days (excluding Fridays - optional)
        $working_days = 0;
        for ($day = 1; $day <= $total_days; $day++) {
            $date = $year . '-' . sprintf('%02d', $month_num) . '-' . sprintf('%02d', $day);
            $day_of_week = date('N', strtotime($date));
            if ($day_of_week != 5) { // Exclude Friday (5)
                $working_days++;
            }
        }
        
        // Get attendance for the employee for the month
        $stmt = $pdo->prepare("SELECT date, status, is_approved 
                               FROM employee_attendance 
                               WHERE employee_id = ? 
                               AND YEAR(date) = ? 
                               AND MONTH(date) = ?");
        $stmt->execute([$employee_id, $year, $month_num]);
        $attendances = $stmt->fetchAll();
        
        // Count unexcused absences
        $unexcused_absences = 0;
        $leave_days = 0;
        $present_days = 0;
        
        foreach ($attendances as $att) {
            $status = $att['status'];
            if ($status == 'present' || $status == 'late' || $status == 'half_day') {
                $present_days++;
            } elseif ($status == 'absent' && $att['is_approved'] == 0) {
                $unexcused_absences++;
            } elseif ($status == 'leave' || $status == 'sick_leave' || $status == 'casual_leave' || $status == 'emergency_leave') {
                $leave_days++;
            }
        }
        
        // Check for any unapproved leaves
        $stmt = $pdo->prepare("SELECT COUNT(*) as count 
                               FROM employee_leaves 
                               WHERE employee_id = ? 
                               AND status != 'approved'
                               AND start_date <= ? 
                               AND end_date >= ?");
        $stmt->execute([$employee_id, $month . '-01', $month . '-' . $total_days]);
        $unapproved_leaves = $stmt->fetch()['count'];
        
        // Calculate daily salary
        $daily_salary = $working_days > 0 ? $employee['base_salary'] / $working_days : 0;
        
        // Calculate deduction (only for unexcused absences)
        $deduction_amount = $unexcused_absences * $daily_salary;
        
        // Add unapproved leaves to deduction
        $deduction_amount += $unapproved_leaves * $daily_salary;
        
        // Prepare response
        $response = [
            'employee_id' => $employee_id,
            'month' => $month,
            'total_days' => $total_days,
            'working_days' => $working_days,
            'present_days' => $present_days,
            'unexcused_absences' => $unexcused_absences,
            'leave_days' => $leave_days,
            'unapproved_leaves' => $unapproved_leaves,
            'base_salary' => $employee['base_salary'],
            'daily_salary' => round($daily_salary, 2),
            'deduction_amount' => round($deduction_amount, 2),
            'absence_details' => []
        ];
        
        // Get detailed absence list
        foreach ($attendances as $att) {
            if (($att['status'] == 'absent' && $att['is_approved'] == 0) || 
                $att['status'] == 'absent') {
                $response['absence_details'][] = [
                    'date' => $att['date'],
                    'status' => $att['status'],
                    'is_approved' => $att['is_approved']
                ];
            }
        }
        
        echo json_encode($response);
        
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
    }
} else {
    echo json_encode(['error' => 'Invalid parameters']);
}
?>