<?php
session_start();
include '../layouts/dbconn.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$transactionId = $_POST['transaction_id'] ?? 0;
$visitId = $_POST['visit_id'] ?? 0;
$notes = $_POST['notes'] ?? '';

$conn->begin_transaction();

try {
    // Get M-Pesa transaction details
    $stmt = $conn->prepare("SELECT amount, mpesa_receipt_number FROM mpesa_transactions WHERE id = ?");
    $stmt->bind_param('i', $transactionId);
    $stmt->execute();
    $mpesa = $stmt->get_result()->fetch_assoc();
    
    if (!$mpesa) {
        throw new Exception('M-Pesa transaction not found');
    }

    // Update M-Pesa transaction
    $stmt = $conn->prepare("UPDATE mpesa_transactions SET visit_id = ?, status = 'COMPLETED' WHERE id = ?");
    $stmt->bind_param('ii', $visitId, $transactionId);
    $stmt->execute();

    // Create payment record
    $stmt = $conn->prepare("INSERT INTO payments (visit_id, payment_method, amount, reference_number, notes, status, created_by, created_at) VALUES (?, 'M-PESA', ?, ?, ?, 'COMPLETED', ?, NOW())");
    $paymentMethod = 'M-PESA';
    $stmt->bind_param('idssi', $visitId, $mpesa['amount'], $mpesa['mpesa_receipt_number'], $notes, $_SESSION['user_id']);
    $stmt->execute();

    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'M-Pesa payment successfully linked to invoice'
    ]);

} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>