<?php
/**
 * API Endpoint: Refresh Attendance Data
 * Loads all registered employees and creates attendance records for them
 */

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

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($input['month']) || !isset($input['year']) || !isset($input['site_id'])) {
        throw new Exception('Missing required parameters');
    }
    
    $month = $input['month'];
    $year = $input['year'];
    $siteId = (int)$input['site_id'];
    
    // Convert year to 2-digit format if needed
    $year = preg_replace('/\D/', '', $year);
    if (strlen($year) === 4) {
        $year = substr($year, -2);
    }
    
    // Format: Jan-25
    $attendanceMonth = $month . '-' . $year;
    
    $db = getDB();
    $db->beginTransaction();
    
    try {
        // Check if period exists
        $periodCheck = $db->prepare("SELECT period_id FROM attendance_periods WHERE attendance_month = ? AND site_id = ?");
        $periodCheck->execute([$attendanceMonth, $siteId]);
        $periodExists = $periodCheck->fetch();
        
        if (!$periodExists) {
            // Create the period first
            // Generate period_display (e.g., "December 2025")
            $monthNames = [
                'Jan' => 'January', 'Feb' => 'February', 'Mar' => 'March', 'Apr' => 'April',
                'May' => 'May', 'Jun' => 'June', 'Jul' => 'July', 'Aug' => 'August',
                'Sep' => 'September', 'Oct' => 'October', 'Nov' => 'November', 'Dec' => 'December'
            ];
            $fullYear = '20' . $year;
            $periodDisplay = ($monthNames[$month] ?? $month) . ' ' . $fullYear;
            
            $createPeriod = $db->prepare("
                INSERT INTO attendance_periods (site_id, attendance_month, period_display, created_at)
                VALUES (?, ?, ?, NOW())
            ");
            $createPeriod->execute([$siteId, $attendanceMonth, $periodDisplay]);
        }
        
        // Get ALL active employees for this site
        $employeesStmt = $db->prepare("
            SELECT employee_id 
            FROM employees 
            WHERE site_id = ? AND employment_status = 'active'
            ORDER BY employee_code
        ");
        $employeesStmt->execute([$siteId]);
        $employees = $employeesStmt->fetchAll(PDO::FETCH_ASSOC);
        
        $created = 0;
        $updated = 0;
        
        // Create attendance records for all employees - Realtime sync with employees table
        foreach ($employees as $emp) {
            $employeeId = $emp['employee_id'];
            
            // Check if attendance record already exists - Date-wise check
            $checkStmt = $db->prepare("
                SELECT attendance_grid_id 
                FROM attendance_monthly_grid 
                WHERE employee_id = ? AND attendance_month = ? AND site_id = ?
            ");
            $checkStmt->execute([$employeeId, $attendanceMonth, $siteId]);
            $existing = $checkStmt->fetch();
            
            if (!$existing) {
                // Create new attendance record
                $insertStmt = $db->prepare("
                    INSERT INTO attendance_monthly_grid 
                    (site_id, employee_id, attendance_month, created_at, updated_at)
                    VALUES (?, ?, ?, NOW(), NOW())
                ");
                $insertStmt->execute([$siteId, $employeeId, $attendanceMonth]);
                $created++;
            } else {
                $updated++;
            }
        }
        
        // Update period employee count
        $updatePeriod = $db->prepare("
            UPDATE attendance_periods 
            SET employee_count = (SELECT COUNT(*) FROM attendance_monthly_grid WHERE attendance_month = ? AND site_id = ?)
            WHERE attendance_month = ? AND site_id = ?
        ");
        $updatePeriod->execute([$attendanceMonth, $siteId, $attendanceMonth, $siteId]);
        
        $db->commit();
        
        echo json_encode([
            'success' => true,
            'message' => "Attendance data refreshed successfully. Created: {$created}, Already exists: {$updated}",
            'created' => $created,
            'updated' => $updated,
            'total_employees' => count($employees)
        ]);
        
    } catch (Exception $e) {
        $db->rollBack();
        throw $e;
    }
    
} catch (Exception $e) {
    error_log("Refresh attendance data API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

