<?php
// test_cancel_and_locks.php

$runner = 'php "' . __DIR__ . '/api_runner.php"';

function callApi($action, $data = []) {
    global $runner;
    $data['action'] = $action;
    $json = json_encode($data);
    // Escape JSON string for Windows command line (double quotes need to be escaped as \")
    $escapedJson = str_replace('"', '\"', $json);
    $cmd = "$runner \"$escapedJson\"";
    $output = shell_exec($cmd);
    return json_decode($output, true) ?: ['raw_output' => $output];
}

echo "=== STARTING E2E API VERIFICATION TESTS ===\n\n";

// ----------------------------------------------------
// Test 1: Create a Pending Invoice
// ----------------------------------------------------
echo "Test 1: Creating a pending invoice...\n";
$createData = [
    'buyer_name' => 'E2E Test Buyer',
    'buyer_brand' => 'E2E Brand',
    'buyer_contact' => 'E2E Contact',
    'buyer_email' => 'e2e@test.com',
    'buyer_phone' => '1234567890',
    'buyer_country' => 'Sri Lanka',
    'product_name' => 'E2E Test Shirt',
    'product_sku' => 'E2E-SH-001',
    'product_desc' => 'Test shirt description',
    'units_completed' => 100,
    'unit_price' => 12.50,
    'taxes_vat' => 25.00,
    'discounts' => 10.00,
    'shipping_charges' => 15.00,
    'po_reference' => 'PO-E2E-001',
    'payment_terms' => 'Net 30',
    'payment_term_id' => 1,
    'due_date' => '2026-06-30',
    'status' => 'Pending'
];

$res1 = callApi('create', $createData);
if (isset($res1['success']) && $res1['success']) {
    $invoiceId = $res1['invoice_id'];
    $invoiceNum = $res1['invoice_number'];
    echo "SUCCESS: Created Invoice ID: $invoiceId, Number: $invoiceNum\n\n";
} else {
    echo "FAIL: Failed to create invoice.\n";
    print_r($res1);
    exit(1);
}

// ----------------------------------------------------
// Test 2: Cancel the Pending Invoice
// ----------------------------------------------------
echo "Test 2: Cancelling the pending invoice (ID: $invoiceId)...\n";
$res2 = callApi('cancel_invoice', ['id' => $invoiceId]);
if (isset($res2['success']) && $res2['success']) {
    echo "SUCCESS: " . $res2['message'] . "\n\n";
} else {
    echo "FAIL: Failed to cancel invoice.\n";
    print_r($res2);
}

// Verify status is indeed Cancelled
echo "Verifying status is 'Cancelled'...\n";
$resGet = callApi('get', ['id' => $invoiceId]);
if (isset($resGet['invoice']) && $resGet['invoice']['status'] === 'Cancelled') {
    echo "SUCCESS: Verified invoice status is 'Cancelled'\n\n";
} else {
    echo "FAIL: Invoice status is: " . ($resGet['invoice']['status'] ?? 'unknown') . "\n\n";
}

// ----------------------------------------------------
// Test 3: Attempt to edit/update a Cancelled Invoice
// ----------------------------------------------------
echo "Test 3: Attempting to update a Cancelled Invoice...\n";
$updateData = $createData;
$updateData['id'] = $invoiceId;
$updateData['status'] = 'Issued';
$res3 = callApi('update', $updateData);
if (isset($res3['success']) && !$res3['success']) {
    echo "SUCCESS: Blocked editing Cancelled Invoice. Error: " . $res3['message'] . "\n\n";
} else {
    echo "FAIL: Editing Cancelled Invoice succeeded or returned unexpected result:\n";
    print_r($res3);
    echo "\n";
}

// ----------------------------------------------------
// Test 4: Create another Invoice and make it Paid
// ----------------------------------------------------
echo "Test 4: Creating a second invoice to test Paid restrictions...\n";
$res4 = callApi('create', $createData);
if (isset($res4['success']) && $res4['success']) {
    $paidInvoiceId = $res4['invoice_id'];
    $paidInvoiceNum = $res4['invoice_number'];
    echo "SUCCESS: Created Second Invoice ID: $paidInvoiceId, Number: $paidInvoiceNum\n\n";
} else {
    echo "FAIL: Failed to create second invoice.\n";
    print_r($res4);
    exit(1);
}

// ----------------------------------------------------
// Test 4.1: Attempt to update buyer details on Pending Invoice
// ----------------------------------------------------
echo "Test 4.1: Attempting to update buyer details on a Pending Invoice...\n";
$updateBuyerData = $createData;
$updateBuyerData['id'] = $paidInvoiceId;
$updateBuyerData['buyer_name'] = 'UPDATED Buyer Name';
$updateBuyerData['buyer_brand'] = 'UPDATED Brand';
$resUpdateBuyer = callApi('update', $updateBuyerData);
if (isset($resUpdateBuyer['success']) && $resUpdateBuyer['success']) {
    echo "SUCCESS: Updated buyer details on Pending invoice.\n";
    // Fetch it to verify database persistence
    $resGet2 = callApi('get', ['id' => $paidInvoiceId]);
    if (isset($resGet2['invoice'])) {
        $buyerDetailsDb = $resGet2['invoice']['buyer_details'];
        if (strpos($buyerDetailsDb, 'Name: UPDATED Buyer Name') !== false && strpos($buyerDetailsDb, 'Brand: UPDATED Brand') !== false) {
            echo "SUCCESS: Verified buyer details updated in the database.\n\n";
        } else {
            echo "FAIL: Buyer details in database do not match updated values. Content: \n$buyerDetailsDb\n\n";
        }
    } else {
        echo "FAIL: Failed to fetch invoice details to verify database persistence.\n\n";
    }
} else {
    echo "FAIL: Updating buyer details on Pending invoice returned error:\n";
    print_r($resUpdateBuyer);
    echo "\n";
}

// Let's add a payment that fully pays the invoice.
// Grand Total = (100 * 12.50) + 25.00 + 15.00 - 10.00 = 1250.00 + 30.00 = 1280.00
$grandTotal = (100 * 12.50) + 25.00 + 15.00 - 10.00;
echo "Recording full payment of $grandTotal to make it 'Paid'...\n";
$resPay = callApi('add_payment', [
    'invoice_id' => $paidInvoiceId,
    'amount' => $grandTotal,
    'payment_date' => '2026-05-22',
    'payment_method' => 'Bank Transfer',
    'reference_no' => 'REF-PAID-TEST',
    'notes' => 'Full payment'
]);

if (isset($resPay['success']) && $resPay['success']) {
    echo "SUCCESS: Recorded payment. New status: " . $resPay['invoice_status'] . "\n";
    $payments = $resPay['payments'];
    $paymentId = $payments[0]['id'];
    echo "Payment ID recorded: $paymentId\n\n";
} else {
    echo "FAIL: Failed to record payment.\n";
    print_r($resPay);
    exit(1);
}

// ----------------------------------------------------
// Test 5: Attempt to cancel a Paid Invoice
// ----------------------------------------------------
echo "Test 5: Attempting to cancel the Paid invoice (ID: $paidInvoiceId)...\n";
$resCancelPaid = callApi('cancel_invoice', ['id' => $paidInvoiceId]);
if (isset($resCancelPaid['success']) && !$resCancelPaid['success']) {
    echo "SUCCESS: Blocked cancelling Paid Invoice. Error: " . $resCancelPaid['message'] . "\n\n";
} else {
    echo "FAIL: Cancelled a Paid Invoice!\n";
    print_r($resCancelPaid);
    echo "\n";
}

// ----------------------------------------------------
// Test 6: Attempt to edit/update a Paid Invoice
// ----------------------------------------------------
echo "Test 6: Attempting to update the Paid Invoice...\n";
$updateDataPaid = $createData;
$updateDataPaid['id'] = $paidInvoiceId;
$updateDataPaid['units_completed'] = 120; // try to edit quantity
$resUpdatePaid = callApi('update', $updateDataPaid);
if (isset($resUpdatePaid['success']) && !$resUpdatePaid['success']) {
    echo "SUCCESS: Blocked editing Paid Invoice. Error: " . $resUpdatePaid['message'] . "\n\n";
} else {
    echo "FAIL: Editing Paid Invoice succeeded or returned unexpected result:\n";
    print_r($resUpdatePaid);
    echo "\n";
}

// ----------------------------------------------------
// Test 7: Attempt to delete payment from a Paid Invoice
// ----------------------------------------------------
echo "Test 7: Attempting to delete a payment from the Paid Invoice...\n";
$resDeletePmt = callApi('delete_payment', [
    'invoice_id' => $paidInvoiceId,
    'payment_id' => $paymentId
]);
if (isset($resDeletePmt['success']) && !$resDeletePmt['success']) {
    echo "SUCCESS: Blocked deleting payment from Paid Invoice. Error: " . $resDeletePmt['message'] . "\n\n";
} else {
    echo "FAIL: Deleted payment from a Paid Invoice!\n";
    print_r($resDeletePmt);
    echo "\n";
}

echo "=== ALL API TESTS COMPLETED ===\n";
