<?php
// PayrollAPI.php

// Include the reusable CORS handler
require_once __DIR__ . '/cors.php';


require_once __DIR__ . '/db.php'; // This defines $pdo
require_once __DIR__ . '/PayrollProcessor.php'; // Include the PayrollProcessor

// Function for sending JSON response and exiting
function sendJsonResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit();
}

// Handle request
switch ($_SERVER['REQUEST_METHOD']) {
    case 'POST':
        $input = file_get_contents('php://input'); // Get raw input
        error_log("PayrollAPI Raw JSON Input: " . $input); // Log raw input

        $data = json_decode($input, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log("PayrollAPI JSON Decode Error: " . json_last_error_msg());
            sendJsonResponse(['error' => 'Invalid JSON received: ' . json_last_error_msg()], 400);
        }
        error_log("PayrollAPI Decoded JSON Data: " . print_r($data, true)); // Log decoded data

        // This API's primary action is to run payroll
        $action = $data['action'] ?? '';

        if ($action === 'run_payroll') {
            $pay_period_month = $data['pay_period_month'] ?? null;
            $pay_period_year = $data['pay_period_year'] ?? null;
            $region = $data['region'] ?? 'all';
            // >>> MODIFICATION START <<<
            // The frontend sends transaction_type: null when 'All Payroll Types' is selected.
            // We should capture that null directly.
            $transaction_type_filter = $data['transaction_type'] ?? null;
            // >>> MODIFICATION END <<<

            $emp_no_to_process = $data['empNo'] ?? null;

            $custom_additions = $data['custom_additions'] ?? [];
            $custom_deductions = $data['custom_deductions'] ?? [];

            // Log the custom data received *before* passing to processor
            error_log("PayrollAPI Custom Additions Received: " . print_r($custom_additions, true));
            error_log("PayrollAPI Custom Deductions Received: " . print_r($custom_deductions, true));

            if (!$pay_period_month || !$pay_period_year) {
                sendJsonResponse(['error' => 'Pay period month and year are required for payroll calculation.'], 400);
            }

            // Instantiate PayrollProcessor
            $payrollProcessor = new PayrollProcessor($pdo);

            try {
                // Call the PayrollProcessor to calculate and save payroll
                $count = $payrollProcessor->processPayroll(
                    $pay_period_month,
                    (int)$pay_period_year, // Ensure year is int
                    $region,
                    $transaction_type_filter, // Pass the filter (which can be null) to the processor
                    $emp_no_to_process, // <-- Pass the empNo to process
                    $custom_additions,  // <-- Pass custom additions
                    $custom_deductions  // <-- Pass custom deductions
                );

                $message = "Payroll calculated and saved for $count employees.";
                if ($emp_no_to_process !== null) {
                    $message = $count > 0 ? "Payroll processed successfully for one employee." : "No active employee found with that Employee Number for the specified period.";
                }

                sendJsonResponse([
                    "message" => $message,
                    "calculated_count" => $count
                ]);
            } catch (Exception $e) {
                error_log("Payroll Processor Error: " . $e->getMessage()); // Log exception
                sendJsonResponse(['error' => 'Payroll calculation failed: ' . $e->getMessage()], 500);
            }
        } else {
            sendJsonResponse(["error" => "Invalid action for this API."], 400);
        }
        break;

    default:
        sendJsonResponse(["error" => "Method not allowed"], 405);
        break;
}
?>