<?php
$workspace_path = "c:\\Users\\User\\Documents\\Antigravity Projects\\Apperal Managment System -Vanila- PHP";
chdir($workspace_path);

require_once 'includes/db.php';

echo "--- RUNNING PAYMENT COLLECTION BACKEND TESTS ---\n";

function executeApiRequest($payload) {
    $workspace_path = "c:\\Users\\User\\Documents\\Antigravity Projects\\Apperal Managment System -Vanila- PHP";
    $base64 = base64_encode(json_encode($payload));
    $cmd = "php -f scratch/run_api.php -- " . escapeshellarg($base64);
    
    // Execute subprocess
    $output = shell_exec("cd " . escapeshellarg($workspace_path) . " && " . $cmd);
    return json_decode($output, true);
}

// 1. Create a test invoice
$buyer_name = "Payment Test Buyer";
$buyer_details = "Name: $buyer_name\nBrand: Test Brand\nContact: Test Contact\nEmail: test@buyer.com\nPhone: 123456\nCountry: Sri Lanka";
$product_details = "Name: Test Product\nSKU: TEST-PROD-999\nDescription: For payment testing";
$invoice_number = "INV-T-" . mt_rand(1000000, 9999999);

query("
    INSERT INTO production_invoices 
        (company_id, invoice_number, buyer_details, product_details, units_completed, unit_price, total_amount, taxes_vat, discounts, shipping_charges, payment_terms, status, due_date, created_at)
    VALUES (1, ?, ?, ?, 10, 100.00, 1000.00, 100.00, 50.00, 150.00, 'Net 30', 'Pending', '2026-06-30', NOW())
", [$invoice_number, $buyer_details, $product_details]);

$invoice_id = lastInsertId();
// Grand Total = 1000 + 100 + 150 - 50 = 1200 LKR
echo "Created test invoice $invoice_number (ID: $invoice_id). Grand Total: 1200.00 LKR. Current status: Pending\n";

// 2. Add partial payment of 500 LKR
$res1 = executeApiRequest([
    'action' => 'add_payment',
    'invoice_id' => $invoice_id,
    'amount' => 500.00,
    'payment_date' => '2026-05-22',
    'payment_method' => 'Bank Transfer',
    'reference_no' => 'REF-PARTIAL',
    'notes' => 'First partial payment'
]);

if ($res1 && isset($res1['success']) && $res1['success']) {
    echo "SUCCESS: Recorded partial payment of 500 LKR. Updated Invoice Status: {$res1['invoice_status']}\n";
    $p1 = $res1['payments'][0];
    $payment1_id = $p1['id'];
} else {
    echo "FAILED: " . ($res1['message'] ?? 'No response') . "\n";
    // Clean up
    query("DELETE FROM production_invoices WHERE id = ?", [$invoice_id]);
    exit(1);
}

// 3. Add second payment of 700 LKR (making total paid = 1200 LKR, which fully pays the invoice)
$res2 = executeApiRequest([
    'action' => 'add_payment',
    'invoice_id' => $invoice_id,
    'amount' => 700.00,
    'payment_date' => '2026-05-22',
    'payment_method' => 'Cash',
    'reference_no' => 'REF-FINAL',
    'notes' => 'Second payment'
]);

if ($res2 && isset($res2['success']) && $res2['success']) {
    echo "SUCCESS: Recorded final payment of 700 LKR. Updated Invoice Status: {$res2['invoice_status']}\n";
} else {
    echo "FAILED: " . ($res2['message'] ?? 'No response') . "\n";
    // Clean up
    query("DELETE FROM production_invoices WHERE id = ?", [$invoice_id]);
    exit(1);
}

// 4. Fetch payments to verify we have both
$res3 = executeApiRequest([
    'action' => 'get_payments',
    'invoice_id' => $invoice_id
]);

if ($res3 && isset($res3['success']) && $res3['success']) {
    echo "SUCCESS: Retrieved payments list. Count: " . count($res3['payments']) . "\n";
} else {
    echo "FAILED: " . ($res3['message'] ?? 'No response') . "\n";
    // Clean up
    query("DELETE FROM production_invoices WHERE id = ?", [$invoice_id]);
    exit(1);
}

// 5. Delete one payment (the 700 LKR cash payment)
$cash_payment_id = null;
foreach ($res3['payments'] as $p) {
    if ($p['payment_method'] === 'Cash') {
        $cash_payment_id = $p['id'];
        break;
    }
}

if ($cash_payment_id) {
    $res4 = executeApiRequest([
        'action' => 'delete_payment',
        'invoice_id' => $invoice_id,
        'payment_id' => $cash_payment_id
    ]);
    
    if ($res4 && isset($res4['success']) && $res4['success']) {
        echo "SUCCESS: Deleted 700 LKR payment. Updated Invoice Status: {$res4['invoice_status']}\n";
    } else {
        echo "FAILED: " . ($res4['message'] ?? 'No response') . "\n";
        // Clean up
        query("DELETE FROM production_invoices WHERE id = ?", [$invoice_id]);
        exit(1);
    }
} else {
    echo "FAILED: Could not find cash payment to delete.\n";
    // Clean up
    query("DELETE FROM production_invoices WHERE id = ?", [$invoice_id]);
    exit(1);
}

// 6. Delete the other payment (the 500 LKR bank transfer payment)
$res5 = executeApiRequest([
    'action' => 'delete_payment',
    'invoice_id' => $invoice_id,
    'payment_id' => $payment1_id
]);

if ($res5 && isset($res5['success']) && $res5['success']) {
    echo "SUCCESS: Deleted 500 LKR payment. Updated Invoice Status: {$res5['invoice_status']}\n";
} else {
    echo "FAILED: " . ($res5['message'] ?? 'No response') . "\n";
    // Clean up
    query("DELETE FROM production_invoices WHERE id = ?", [$invoice_id]);
    exit(1);
}

// Clean up test invoice
query("DELETE FROM production_invoices WHERE id = ?", [$invoice_id]);
echo "Test invoice cleaned up from database.\n";
echo "--- ALL TESTS COMPLETED SUCCESSFULLY ---\n";
?>
