<?php
include_once('../includes/config.php');

try {
    // Get JSON input
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        throw new Exception('Invalid JSON input');
    }

    $paymentId = $input['payment_id'] ?? '';
    $transactionDate = $input['transaction_date'] ?? '';
    $paymentMethod = $input['payment_method'] ?? '';
    $amount = $input['amount'] ?? '';
    $referenceNumber = $input['reference_number'] ?? '';
    $description = $input['description'] ?? '';
    $status = $input['status'] ?? '';

    if (empty($paymentId)) {
        throw new Exception('Payment ID is required');
    }

    // Validate required fields
    if (empty($transactionDate) || empty($paymentMethod) || empty($amount) || empty($status)) {
        throw new Exception('Transaction date, payment method, amount, and status are required');
    }

    // Validate amount
    if (!is_numeric($amount) || $amount <= 0) {
        throw new Exception('Amount must be a positive number');
    }

    // Begin transaction
    $dbh->beginTransaction();

    // Update POS sale record
    $updateQuery = "
        UPDATE tblpossales 
        SET 
            SaleDate = ?,
            PaymentMethod = ?,
            TotalAmount = ?,
            ReferenceNumber = ?,
            Notes = ?,
            PaymentStatus = ?,
            UpdatedAt = NOW()
        WHERE ID = ?
    ";

    $stmt = $dbh->prepare($updateQuery);
    $result = $stmt->execute([
        $transactionDate,
        $paymentMethod,
        $amount,
        $referenceNumber,
        $description,
        $status,
        $paymentId
    ]);

    if (!$result) {
        throw new Exception('Failed to update sale record');
    }

    // Check if any rows were affected
    if ($stmt->rowCount() === 0) {
        throw new Exception('Sale record not found or no changes made');
    }

    // Commit transaction
    $dbh->commit();

    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'message' => 'Payment updated successfully'
    ]);

} catch (PDOException $e) {
    if ($dbh->inTransaction()) {
        $dbh->rollBack();
    }
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    if ($dbh->inTransaction()) {
        $dbh->rollBack();
    }
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
