<?php
/**
 * API Endpoint: Bulk Save Overtime Data
 * Saves overtime data for multiple employees at once
 */

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['employees'])) {
        throw new Exception('Invalid request data');
    }
    
    $selectedMonth = (int)$input['month'];
    $selectedYear = (int)$input['year'];
    $employeesData = $input['employees'];
    
    // Validate
    if ($selectedMonth < 1 || $selectedMonth > 12) {
        throw new Exception('Invalid month');
    }
    if ($selectedYear < 2000 || $selectedYear > 2100) {
        throw new Exception('Invalid year');
    }
    
    $siteId = getCurrentSiteId();
    $userId = getCurrentUserId();
    $db = getDB();
    
    // Format attendance month
    $attendanceMonth = date('M-y', mktime(0, 0, 0, $selectedMonth, 1, $selectedYear));
    
    // Check if table exists
    $checkTable = $db->query("SHOW TABLES LIKE 'overtime_monthly_grid'");
    if ($checkTable->rowCount() == 0) {
        throw new Exception('Overtime grid table does not exist');
    }
    
    $db->beginTransaction();
    
    $savedCount = 0;
    $errors = [];
    
    foreach ($employeesData as $empData) {
        try {
            $employeeId = (int)($empData['employee_id'] ?? 0);
            $dayValues = $empData['day_values'] ?? [];
            $overtimeRate = (float)($empData['overtime_rate'] ?? 0);
            $earnAmount = (float)($empData['earn_amount'] ?? 0);
            
            if ($employeeId <= 0) continue;
            
            // Get employee details
            $empStmt = $db->prepare("SELECT employee_code, first_name, last_name FROM employees WHERE employee_id = ? AND site_id = ?");
            $empStmt->execute([$employeeId, $siteId]);
            $employee = $empStmt->fetch();
            
            if (!$employee) continue;
            
            // Get designation name
            $designationName = '';
            $desigStmt = $db->prepare("SELECT d.designation_name FROM employees e LEFT JOIN designations d ON e.designation_id = d.designation_id WHERE e.employee_id = ?");
            $desigStmt->execute([$employeeId]);
            $desig = $desigStmt->fetch();
            if ($desig) {
                $designationName = $desig['designation_name'];
            }
            
            // Check if record exists
            $checkStmt = $db->prepare("SELECT overtime_grid_id FROM overtime_monthly_grid WHERE employee_id = ? AND attendance_month = ?");
            $checkStmt->execute([$employeeId, $attendanceMonth]);
            $existing = $checkStmt->fetch();
            
            if ($existing) {
                // Update existing record
                $updateFields = [];
                $updateValues = [];
                
                for ($day = 1; $day <= 31; $day++) {
                    $dayKey = 'day_' . $day;
                    $hours = isset($dayValues[$dayKey]) ? (float)$dayValues[$dayKey] : 0;
                    $updateFields[] = "`{$dayKey}` = ?";
                    $updateValues[] = $hours;
                }
                
                $updateFields[] = "`overtime_rate` = ?";
                $updateValues[] = $overtimeRate;
                
                $updateFields[] = "`earn_amount` = ?";
                $updateValues[] = $earnAmount;
                
                $updateFields[] = "`updated_at` = NOW()";
                
                $updateValues[] = $employeeId;
                $updateValues[] = $attendanceMonth;
                
                $sql = "UPDATE overtime_monthly_grid SET " . implode(', ', $updateFields) . 
                       " WHERE employee_id = ? AND attendance_month = ?";
                
                $updateStmt = $db->prepare($sql);
                $updateStmt->execute($updateValues);
            } else {
                // Insert new record
                $dayColumns = [];
                $dayPlaceholders = [];
                $insertValues = [];
                
                for ($day = 1; $day <= 31; $day++) {
                    $dayKey = 'day_' . $day;
                    $hours = isset($dayValues[$dayKey]) ? (float)$dayValues[$dayKey] : 0;
                    $dayColumns[] = "`{$dayKey}`";
                    $dayPlaceholders[] = "?";
                    $insertValues[] = $hours;
                }
                
                $sql = "INSERT INTO overtime_monthly_grid 
                        (site_id, employee_id, attendance_month, emp_id, designation, " . 
                        implode(', ', $dayColumns) . ", overtime_rate, earn_amount, created_at, updated_at) 
                        VALUES (?, ?, ?, ?, ?, " . implode(', ', $dayPlaceholders) . ", ?, ?, NOW(), NOW())";
                
                $insertValues = array_merge(
                    [$siteId, $employeeId, $attendanceMonth, $employee['employee_code'], $designationName],
                    $insertValues,
                    [$overtimeRate, $earnAmount]
                );
                
                $insertStmt = $db->prepare($sql);
                $insertStmt->execute($insertValues);
            }
            
            $savedCount++;
            
        } catch (Exception $e) {
            error_log("Error saving employee {$employeeId}: " . $e->getMessage());
            $errors[] = "Employee ID {$employeeId}: " . $e->getMessage();
        }
    }
    
    $db->commit();
    
    echo json_encode([
        'success' => true,
        'saved_count' => $savedCount,
        'total_count' => count($employeesData),
        'errors' => $errors
    ]);
    
} catch (Exception $e) {
    if (isset($db) && method_exists($db, 'inTransaction') && $db->inTransaction()) {
        $db->rollBack();
    }
    error_log("Bulk save overtime error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

