<?php
/**
 * Fix purchase payment status based on amount_paid vs total
 * Run this script to update existing purchases with incorrect payment status
 */

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/core/Auth.php';

echo "Starting purchase payment status fix...\n";

// Get all purchases
$stmt = db()->prepare("SELECT id, total, amount_paid, payment_status FROM purchases");
$stmt->execute();
$purchases = $stmt->fetchAll();

$updated = 0;
foreach ($purchases as $purchase) {
    $amountPaid = (float)$purchase['amount_paid'];
    $total = (float)$purchase['total'];

    $correctStatus = 'due';
    if ($amountPaid >= $total) {
        $correctStatus = 'paid';
    } elseif ($amountPaid > 0) {
        $correctStatus = 'partial';
    }

    if ($purchase['payment_status'] !== $correctStatus) {
        $updateStmt = db()->prepare("UPDATE purchases SET payment_status = ? WHERE id = ?");
        $updateStmt->execute([$correctStatus, $purchase['id']]);
        $updated++;
        echo "Updated purchase ID {$purchase['id']}: {$purchase['payment_status']} -> {$correctStatus}\n";
    }
}

echo "Fixed $updated purchases.\n";
echo "Done!\n";