<?php
// DisbursementUploadAPI.php
// This API handles the upload of updated disbursement data (remarks, status)
// from the finance team's exported Excel/CSV file.

// 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
ob_start();

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

// Define the allowed origins.
$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 {
    // For unauthorized origins, simply do not set the ACAO header.
    // This will cause a CORS error on the client side, which is intended.
}

header('Access-Control-Allow-Methods: POST, OPTIONS'); // Only POST for upload, OPTIONS for preflight
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'; // Reuse DisbursementsManager

// Function for sending JSON response and exiting
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();
}

// 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':
            $input = file_get_contents('php://input'); // Get raw JSON input
            error_log("DisbursementUploadAPI Raw JSON Input: " . $input); // Log raw input

            $uploadedDisbursements = json_decode($input, true);

            if (json_last_error() !== JSON_ERROR_NONE) {
                error_log("DisbursementUploadAPI JSON Decode Error: " . json_last_error_msg());
                sendJsonResponse(['success' => false, 'message' => 'Invalid JSON received: ' . json_last_error_msg()], 400);
            }

            if (!is_array($uploadedDisbursements) || empty($uploadedDisbursements)) {
                sendJsonResponse(['success' => false, 'message' => 'No valid disbursement data provided for upload.'], 400);
            }

            $updatedCount = 0;
            $failedUpdates = [];

            foreach ($uploadedDisbursements as $disbursementData) {
                $id = $disbursementData['id'] ?? null;
                $remarks = $disbursementData['remarks'] ?? null;
                $status = $disbursementData['status'] ?? null; // Assume status can also be updated

                // Only proceed if a valid ID is present
                if ($id) {
                    try {
                        // Call a method in DisbursementsManager to update remarks/status
                        // This method needs to be implemented in DisbursementsManager.php
                        $isUpdated = $disbursementsManager->updateDisbursementRemarksAndStatus($id, $remarks, $status);
                        if ($isUpdated) {
                            $updatedCount++;
                        } else {
                            $failedUpdates[] = ['id' => $id, 'reason' => 'Disbursement not found or no change.'];
                        }
                    } catch (Exception $e) {
                        error_log("DisbursementUploadAPI Update Error for ID {$id}: " . $e->getMessage());
                        $failedUpdates[] = ['id' => $id, 'reason' => $e->getMessage()];
                    }
                } else {
                    $failedUpdates[] = ['id' => 'N/A', 'reason' => 'Missing ID in record.'];
                }
            }

            $message = "$updatedCount disbursements updated successfully.";
            if (!empty($failedUpdates)) {
                $message .= " " . count($failedUpdates) . " failed updates. Check details.";
                sendJsonResponse([
                    'success' => true, // Still success if some worked
                    'message' => $message,
                    'updated_count' => $updatedCount,
                    'failed_updates' => $failedUpdates
                ], 200); // Or 207 Multi-Status, but 200 with details is common for partial success
            } else {
                sendJsonResponse([
                    'success' => true,
                    'message' => $message,
                    'updated_count' => $updatedCount
                ], 200);
            }
            break;

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

// If for some reason sendJsonResponse was not called, send a generic error.
ob_end_clean();
error_log("DisbursementUploadAPI reached end of script without sending JSON response.");
sendJsonResponse(['success' => false, 'message' => 'An unexpected server error occurred.'], 500);