<?php
// End-to-end test for payment module via HTTP
$base = 'http://127.0.0.1:8080';

// We need a cookie jar for session
$cookieFile = tempnam(sys_get_temp_dir(), 'cookie_');

function httpPost($url, $data, $cookieFile) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_COOKIEJAR  => $cookieFile,
        CURLOPT_COOKIEFILE => $cookieFile,
        CURLOPT_TIMEOUT => 10,
    ]);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) return ['curl_error' => $err];
    return json_decode($res, true) ?? ['raw' => $res];
}

function httpGet($url, $cookieFile) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_COOKIEJAR  => $cookieFile,
        CURLOPT_COOKIEFILE => $cookieFile,
        CURLOPT_TIMEOUT => 10,
    ]);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) return ['curl_error' => $err];
    return json_decode($res, true) ?? ['raw' => $res];
}

echo "Step 1: Get invoices list to find an invoice ID...\n";
$result = httpGet("$base/api/invoices.php?action=list", $cookieFile);
if (!isset($result['success'])) {
    echo "FAILED (auth required or server error): ";
    echo json_encode($result) . "\n";
    echo "\nNote: Session required. Test directly in DB instead.\n";
} else if ($result['success']) {
    $invoices = $result['data'] ?? [];
    echo "Found " . count($invoices) . " invoices.\n";
    if (!empty($invoices)) {
        $inv = $invoices[0];
        echo "  -> Invoice ID: {$inv['id']}, Number: {$inv['invoice_number']}, Status: {$inv['status']}\n";
    }
} else {
    echo "API returned: " . json_encode($result) . "\n";
}

echo "\nDirect DB verification:\n";
chdir(dirname(__DIR__));
require_once 'includes/db.php';

$inv = fetch("SELECT id, invoice_number, status, total_amount, taxes_vat, shipping_charges, discounts FROM production_invoices LIMIT 1");
if (!$inv) {
    echo "No invoices found!\n";
    exit;
}

$grand_total = $inv['total_amount'] + $inv['taxes_vat'] + $inv['shipping_charges'] - $inv['discounts'];
echo "Invoice: {$inv['invoice_number']} (ID: {$inv['id']})\n";
echo "Status: {$inv['status']}\n";
echo "Grand Total: $grand_total\n";

// Test add payment
echo "\nAdding partial payment of " . ($grand_total / 2) . "...\n";
$partial = round($grand_total / 2, 2);
query("INSERT INTO invoice_payments (invoice_id, amount, payment_date, payment_method, reference_no, notes) VALUES (?, ?, ?, ?, ?, ?)",
    [$inv['id'], $partial, date('Y-m-d'), 'Bank Transfer', 'REF-TEST-001', 'Test partial payment']);

$totalPaid = (float)fetchValue("SELECT SUM(amount) FROM invoice_payments WHERE invoice_id = ?", [$inv['id']]);
$newStatus = $totalPaid >= $grand_total ? 'Paid' : ($totalPaid > 0 ? 'Partially Paid' : 'Pending');
query("UPDATE production_invoices SET status = ? WHERE id = ?", [$newStatus, $inv['id']]);
echo "  Total Paid: $totalPaid, New Status: $newStatus\n";

$inv2 = fetch("SELECT status FROM production_invoices WHERE id = ?", [$inv['id']]);
echo "  Confirmed status in DB: {$inv2['status']}\n";

// Test delete payment
echo "\nDeleting test payment...\n";
$pid = fetchValue("SELECT id FROM invoice_payments WHERE invoice_id = ? ORDER BY id DESC LIMIT 1", [$inv['id']]);
query("DELETE FROM invoice_payments WHERE id = ?", [$pid]);
$totalPaidAfter = (float)fetchValue("SELECT SUM(amount) FROM invoice_payments WHERE invoice_id = ?", [$inv['id']]);
$revertStatus = $totalPaidAfter >= $grand_total ? 'Paid' : ($totalPaidAfter > 0 ? 'Partially Paid' : ($inv['status'] === 'Issued' ? 'Issued' : 'Pending'));
query("UPDATE production_invoices SET status = ? WHERE id = ?", [$revertStatus, $inv['id']]);
echo "  Total Paid after delete: $totalPaidAfter, Reverted Status: $revertStatus\n";

$inv3 = fetch("SELECT status FROM production_invoices WHERE id = ?", [$inv['id']]);
echo "  Confirmed reverted status: {$inv3['status']}\n";
echo "\nAll tests passed!\n";
