<?php
// DisbursementsAPI.php
// Enable error reporting for development (should be off in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Start output buffering at the very beginning to capture any unexpected output
ob_start();

// Get the origin of the request
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';

// Define the allowed origins. In a production environment, this should be your actual frontend domain(s).
// For development, it's typically http://localhost:3000
$allowed_origins = [
    'http://localhost:3000', // Your frontend's development server
    // Add other production origins when you deploy, e.g., 'https://your-frontend-domain.com'
];

// Check if the current request origin is in the allowed list
if (in_array($origin, $allowed_origins)) {
    header('Access-Control-Allow-Origin: ' . $origin);
} else {
    // Optionally, handle unauthorized origins (e.g., log them or set a restrictive policy)
    // For now, we'll just not set the ACAO header, which will lead to a CORS error for disallowed origins
    // In a strict production setup, you might send a 403 Forbidden header or a more generic ACAO if no credentials are ever involved.
}

header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Allow-Credentials: true'); // *** Crucial: Allow credentials to be sent ***
header('Content-Type: application/json'); // Ensure this header is set early

// Handle preflight (OPTIONS) requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}


// Include necessary files
require_once __DIR__ . '/db.php'; // This should define $pdo
require_once __DIR__ . '/DisbursementsManager.php';
// If you have a separate PayslipPDFGenerator for the download, include it too.
// Make sure this path is correct relative to DisbursementsAPI.php
require_once __DIR__ . '/PayslipPDFGenerator.php';

// Function for sending JSON response and exiting, now also clears buffer
function sendJsonResponse($data, $statusCode = 200) {
    // Clear any buffered output before sending the JSON response
    ob_end_clean();
    http_response_code($statusCode);
    echo json_encode($data);
    exit();
}

// Function for sending PDF response and exiting, now also clears buffer
function sendPdfResponse($pdfContent, $filename, $statusCode = 200) {
    ob_end_clean();
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . strlen($pdfContent));
    http_response_code($statusCode);
    echo $pdfContent;
    exit();
}

// Initialize response array
$response = ['success' => false, 'message' => 'An unknown error occurred.'];

try {
    // Ensure $pdo is available from db.php
    if (!isset($pdo) || !$pdo instanceof PDO) {
        throw new Exception("Database connection (PDO) not available.");
    }

    // Instantiate DisbursementsManager
    $disbursementsManager = new DisbursementsManager($pdo);

    // Handle request based on HTTP method
    switch ($_SERVER['REQUEST_METHOD']) {
        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                sendJsonResponse(['error' => 'Invalid JSON input.'], 400);
            }

            // Check for 'action' parameter to route requests
            $action = $data['action'] ?? '';

            switch ($action) {
                case 'send_payslips':
                    $pay_period_month = $data['pay_period_month'] ?? null;
                    $pay_period_year = $data['pay_period_year'] ?? null;
                    // >>> MODIFICATION START <<<
                    // Pass null for transactionType if not explicitly provided or if 'all' is implied from frontend
                    // However, for send_payslips, it's generally a batch operation for the period,
                    // so transactionType might not be needed or would default to 'all' in the manager.
                    // If your sendPayslips method *does* filter by transaction type, pass it.
                    // Based on your frontend, send_payslips does *not* send transaction_type,
                    // so it's better to NOT default it to 'Salary' here, but rely on the manager's default (which should be 'all'/null)
                    // If $disbursementsManager->generateAndSendPayslips needs it, make sure it's nullable in its signature.
                    // For now, removing the default 'Salary' here as it's not provided by the frontend for this action.
                    // $transactionType = $data['transaction_type'] ?? null;
                    // >>> MODIFICATION END <<<

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

                    try {
                        // Call the method from DisbursementsManager that orchestrates payslip sending
                        // Assuming generateAndSendPayslips in DisbursementsManager does not need transactionType,
                        // or handles null correctly as 'all'. If it requires it, add it back.
                        $status = $disbursementsManager->generateAndSendPayslips(
                            $pay_period_month,
                            (int)$pay_period_year
                            // If generateAndSendPayslips needs transactionType, you would pass it here:
                            // , $transactionType // Uncomment if needed by manager method
                        );

                        if ($status['emails_failed'] === 0) {
                            $response = [
                                'success' => true,
                                'message' => "Payslips successfully sent to {$status['emails_sent']} employees.",
                                'details' => $status
                            ];
                        } else {
                            $response = [
                                'success' => false,
                                'message' => "Completed payslip sending with {$status['emails_failed']} failures and {$status['emails_sent']} successes. Check logs for details.",
                                'details' => $status
                            ];
                        }
                        sendJsonResponse($response);
                    } catch (Exception $e) {
                        error_log("API Error (send_payslips): " . $e->getMessage());
                        sendJsonResponse(['error' => 'Failed to process payslip sending: ' . $e->getMessage()], 500);
                    }
                    break;

                case 'send_single_payslip': // NEW ENDPOINT for sending a single payslip
                    $emp_no = $data['emp_no'] ?? null;
                    $pay_period_month = $data['pay_period_month'] ?? null;
                    $pay_period_year = $data['pay_period_year'] ?? null;
                    // >>> MODIFICATION START <<<
                    // Capture transaction_type, can be null
                    $transactionType = $data['transaction_type'] ?? null;
                    // >>> MODIFICATION END <<<

                    if (!$emp_no || !$pay_period_month || !$pay_period_year) {
                        sendJsonResponse(['error' => 'Employee number, pay period month, and year are required to send a single payslip.'], 400);
                    }

                    try {
                        $result = $disbursementsManager->sendSinglePayslip(
                            $emp_no,
                            $pay_period_month,
                            (int)$pay_period_year,
                            $transactionType // Pass the transactionType
                        );
                        if ($result['status'] === 'success') {
                            sendJsonResponse(['success' => true, 'message' => $result['message']]);
                        } else {
                            sendJsonResponse(['success' => false, 'message' => $result['message']], 500);
                        }
                    } catch (Exception $e) {
                        error_log("API Error (send_single_payslip): " . $e->getMessage());
                        sendJsonResponse(['error' => 'Failed to send single payslip: ' . $e->getMessage()], 500);
                    }
                    break;

                case 'generate_from_employees':
                    // This action is likely deprecated or replaced by PayrollAPI's run_payroll
                    // But if still in use, ensure it handles parameters correctly.
                    // Note: The structure of data for this case seems to use 'Transaction_Date', etc.
                    // which is inconsistent with the 'pay_period_month' etc. used elsewhere.
                    // Make sure your frontend is not calling this method.
                    if (
                        isset($data['Transaction_Date']) &&
                        isset($data['Transaction_Type']) &&
                        isset($data['Region'])
                    ) {
                        $count = $disbursementsManager->generateDisbursementsFromEmployees(
                            $data['Transaction_Date'],
                            $data['Region'],
                            $data['Transaction_Type']
                        );
                        sendJsonResponse([
                            "success" => true,
                            "message" => "Generated $count disbursements successfully (legacy method)."
                        ]);
                    } else {
                        sendJsonResponse(['error' => 'Missing parameters for legacy disbursement generation.'], 400);
                    }
                    break;

                case 'insert_disbursement':
                    $disbursementsManager->insertDisbursement($data);
                    sendJsonResponse(["success" => true, "message" => "Disbursement inserted successfully"]);
                    break;

                default:
                    sendJsonResponse(["error" => "Unknown POST action provided."], 400);
                    break;
            }
            break;

        case 'PUT':
            $id = $_GET['id'] ?? null;
            $data = json_decode(file_get_contents('php://input'), true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                sendJsonResponse(['error' => 'Invalid JSON input.'], 400);
            }

            if (!$id) {
                sendJsonResponse(['error' => 'Disbursement ID is required for update.'], 400);
            }
            $disbursementsManager->updateDisbursement((int)$id, $data); // Cast ID to int
            sendJsonResponse(["success" => true, "message" => "Disbursement updated successfully"]);
            break;

        case 'DELETE':
            $id = $_GET['id'] ?? null;
            if (!$id) {
                sendJsonResponse(['error' => 'Disbursement ID is required for deletion.'], 400);
            }
            $disbursementsManager->deleteDisbursement((int)$id); // Cast ID to int
            sendJsonResponse(["success" => true, "message" => "Disbursement deleted successfully"]);
            break;

        case 'GET':
            $action = $_GET['action'] ?? null;

            if ($action === 'get_disbursements') {
                $pay_period_month = $_GET['pay_period_month'] ?? null;
                $pay_period_year = $_GET['pay_period_year'] ?? null;
                $region = $_GET['region'] ?? 'all';
                // >>> MODIFICATION START <<<
                // This is crucial: 'transaction_type' should be null if 'all' is passed from frontend.
                // Your frontend passes 'null' explicitly. So, just capture it.
                $transaction_type_filter = $_GET['transaction_type'] ?? null; // Can be null, 'Salary', 'Wage'
                // >>> MODIFICATION END <<<

                // ADDED: Read the status parameter from GET
                $status = $_GET['status'] ?? null; // Null if not provided

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

                // MODIFIED: Pass the status parameter and the correct transaction_type_filter to the manager method
                $disbursements = $disbursementsManager->getDisbursementsByPeriodAndFilters(
                    $pay_period_month,
                    (int)$pay_period_year,
                    $region,
                    $transaction_type_filter, // Pass the filter (which can be null)
                    $status // Pass the status parameter here
                );
                // MODIFIED: Wrap the response in 'disbursements' key for frontend consistency
                sendJsonResponse(['disbursements' => $disbursements]);
            } elseif ($action === 'get_single') {
                $id = $_GET['id'] ?? null;
                if (!$id) {
                    sendJsonResponse(['error' => 'Disbursement ID is required to fetch a single disbursement.'], 400);
                }
                $disbursement = $disbursementsManager->getDisbursement((int)$id); // Cast ID to int
                if ($disbursement) {
                    sendJsonResponse($disbursement);
                } else {
                    sendJsonResponse(['message' => 'Disbursement not found.'], 404);
                }
            } elseif ($action === 'get_single_payslip') { // <-- NEW CASE ADDED HERE
                $emp_no = $_GET['emp_no'] ?? null;
                $pay_period_month = $_GET['pay_period_month'] ?? null;
                $pay_period_year = $_GET['pay_period_year'] ?? null;
                // >>> MODIFICATION START <<<
                // Capture transaction_type, can be null
                $transactionType = $_GET['transaction_type'] ?? null;
                // >>> MODIFICATION END <<<

                if (!$emp_no || !$pay_period_month || !$pay_period_year) {
                    sendJsonResponse(['error' => 'Employee number, pay period month, and year are required to get a single payslip.'], 400);
                }

                try {
                    // Assuming getSinglePayslipData returns the full payslip row from the 'payroll' table
                    $payslipData = $disbursementsManager->getSinglePayslipData(
                        $emp_no,
                        $pay_period_month,
                        (int)$pay_period_year,
                        $transactionType // Pass the transactionType
                    );

                    if ($payslipData) {
                        sendJsonResponse($payslipData);
                    } else {
                        // Return an empty object if no payslip is found, consistent with frontend expectation
                        // Changed to return an empty array for consistency with other "not found" cases, or an empty object {}
                        // Based on your frontend code, an empty array `[]` for `payrollData` works for "no data available".
                        sendJsonResponse([]);
                    }
                } catch (Exception $e) {
                    error_log("API Error (get_single_payslip): " . $e->getMessage());
                    sendJsonResponse(['error' => 'Failed to fetch single payslip: ' . $e->getMessage()], 500);
                }
            } elseif ($action === 'download_single_payslip') {
                $emp_no = $_GET['emp_no'] ?? null;
                $pay_period_month = $_GET['pay_period_month'] ?? null;
                $pay_period_year = $_GET['pay_period_year'] ?? null;
                // >>> MODIFICATION START <<<
                // Capture transaction_type, can be null
                $transactionType = $_GET['transaction_type'] ?? null;
                // >>> MODIFICATION END <<<

                if (!$emp_no || !$pay_period_month || !$pay_period_year) {
                    sendJsonResponse(['error' => 'Employee number, pay period month, and year are required to download a single payslip.'], 400);
                }

                try {
                    $payslipData = $disbursementsManager->getSinglePayslipData(
                        $emp_no,
                        $pay_period_month,
                        (int)$pay_period_year,
                        $transactionType // Pass the transactionType
                    );

                    if ($payslipData) {
                        // Ensure PayslipPDFGenerator class is included if used here
                        // For example: require_once __DIR__ . '/PayslipPDFGenerator.php';
                        if (!class_exists('PayslipPDFGenerator')) {
                             throw new Exception("PayslipPDFGenerator class not found. Please ensure it's included correctly in DisbursementsAPI.php.");
                        }
                        $pdfGenerator = new PayslipPDFGenerator(); // Re-instantiate for direct use in API
                        $pdfContent = $pdfGenerator->generatePayslipPdf($payslipData['employee'], $payslipData['payslip']);
                        $filename = $pdfGenerator->getPayslipFilename($payslipData['employee'], $payslipData['payslip']);
                        sendPdfResponse($pdfContent, $filename);
                    } else {
                        sendJsonResponse(['message' => 'Payslip not found for the given criteria.'], 404);
                    }
                } catch (Exception $e) {
                    error_log("API Error (download_single_payslip): " . $e->getMessage());
                    sendJsonResponse(['error' => 'Failed to generate or download payslip: ' . $e->getMessage()], 500);
                }
                break;
            } elseif ($action === 'get_all') {
                $disbursements = $disbursementsManager->getAllDisbursements();
                sendJsonResponse($disbursements);
            } else {
                sendJsonResponse(["error" => "Invalid or missing GET action."], 400);
            }
            break;

        default:
            sendJsonResponse(["error" => "Method not allowed"], 405);
            break;
    }
} catch (PDOException $e) {
    error_log("Database error in DisbursementsAPI: " . $e->getMessage());
    sendJsonResponse(['success' => false, 'message' => 'Database error: ' . $e->getMessage()], 500);
} catch (Exception $e) {
    error_log("Application error in DisbursementsAPI: " . $e->getMessage());
    sendJsonResponse(['success' => false, 'message' => 'Application error: ' . $e->getMessage()], 500);
}

// If for some reason sendJsonResponse was not called (e.g., unexpected code path),
// clean the buffer and send a generic error. This should ideally not be reached.
ob_end_clean();
error_log("DisbursementsAPI reached end of script without sending JSON response.");
sendJsonResponse(['success' => false, 'message' => 'An unexpected server error occurred.'], 500);
?>