<?php
/**
 * Payments API Endpoints
 */

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../classes/Payment.php';
require_once __DIR__ . '/middleware.php';

$method = $_SERVER['REQUEST_METHOD'];
$user = authenticateRequest();
$paymentModel = new Payment();

switch ($method) {
    case 'GET':
        $id = $_GET['id'] ?? null;
        $invoiceId = $_GET['invoice_id'] ?? null;
        $payerId = $_GET['payer_id'] ?? null;
        $propertyId = $_GET['property_id'] ?? null;
        
        if ($id) {
            $payment = $paymentModel->getById($id);
            if ($payment) {
                sendResponse($payment);
            } else {
                sendError('Payment not found', 404);
            }
        } elseif ($invoiceId) {
            $payments = $paymentModel->getPaymentsByInvoice($invoiceId);
            sendResponse(['payments' => $payments]);
        } elseif ($payerId) {
            $filters = [];
            if (isset($_GET['status'])) {
                $filters['status'] = $_GET['status'];
            }
            if (isset($_GET['payment_method'])) {
                $filters['payment_method'] = $_GET['payment_method'];
            }
            
            $payments = $paymentModel->getPaymentsByPayer($payerId, $filters);
            sendResponse(['payments' => $payments]);
        } elseif (isset($_GET['stats'])) {
            $startDate = $_GET['start_date'] ?? null;
            $endDate = $_GET['end_date'] ?? null;
            $stats = $paymentModel->getPaymentStats($propertyId, $startDate, $endDate);
            sendResponse($stats);
        } else {
            sendError('Invalid request', 400);
        }
        break;
        
    case 'POST':
        $action = $_GET['action'] ?? 'record';
        
        if ($action === 'mpesa') {
            // Process MPesa payment
            $data = getJsonBody();
            validateRequired($data, ['payer_id', 'amount', 'mpesa_code', 'phone_number']);
            
            try {
                $paymentId = $paymentModel->processMPesaPayment($data);
                sendResponse(['payment_id' => $paymentId, 'message' => 'MPesa payment processed successfully'], 201);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } elseif ($action === 'bank') {
            // Process bank transfer
            $data = getJsonBody();
            validateRequired($data, ['payer_id', 'amount', 'bank_name', 'account_number', 'reference_number']);
            
            try {
                $paymentId = $paymentModel->processBankTransfer($data);
                sendResponse(['payment_id' => $paymentId, 'message' => 'Bank transfer recorded successfully'], 201);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } elseif ($action === 'card') {
            // Process card payment
            $data = getJsonBody();
            validateRequired($data, ['payer_id', 'amount', 'transaction_id']);
            
            try {
                $paymentId = $paymentModel->processCardPayment($data);
                sendResponse(['payment_id' => $paymentId, 'message' => 'Card payment processed successfully'], 201);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } else {
            // Record general payment
            $data = getJsonBody();
            validateRequired($data, ['payer_id', 'amount', 'payment_method', 'transaction_reference']);
            
            try {
                $paymentId = $paymentModel->recordPayment($data);
                sendResponse(['payment_id' => $paymentId, 'message' => 'Payment recorded successfully'], 201);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        }
        break;
        
    case 'PUT':
        $id = $_GET['id'] ?? null;
        if (!$id) {
            sendError('Payment ID required', 400);
        }
        
        $action = $_GET['action'] ?? 'verify';
        
        if ($action === 'verify') {
            requirePermission('payment.verify');
            
            try {
                $paymentModel->verifyPayment($id, $user['user_id']);
                sendResponse(['message' => 'Payment verified successfully']);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } elseif ($action === 'refund') {
            requirePermission('payment.refund');
            
            $data = getJsonBody();
            $reason = $data['reason'] ?? null;
            
            try {
                $paymentModel->refundPayment($id, $reason);
                sendResponse(['message' => 'Payment refunded successfully']);
            } catch (Exception $e) {
                sendError($e->getMessage(), 400);
            }
        } else {
            sendError('Invalid action', 400);
        }
        break;
        
    default:
        sendError('Method not allowed', 405);
        break;
}
?>
