<?php
require_once 'db/config.php';
require_once 'includes/accounting_helper.php';

echo "Starting Accounting Migration...\n";

$db = db();

// Clear existing journal entries to avoid duplicates if re-running
// But only those that are linked to source types we are migrating
$db->exec("DELETE FROM acc_journal_entries WHERE source_type IN ('invoice', 'payment', 'expense', 'payroll', 'sales_return', 'purchase_return')");
echo "Cleared existing automatic journal entries.\n";

// 1. Invoices
$invoices = $db->query("SELECT * FROM invoices ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
foreach ($invoices as $inv) {
    $items = $db->prepare("SELECT item_id as id, quantity as qty, unit_price as price FROM invoice_items WHERE invoice_id = ?");
    $items->execute([$inv['id']]);
    $items_data = $items->fetchAll(PDO::FETCH_ASSOC);

    if ($inv['type'] === 'sale') {
        recordSaleJournal($inv['id'], (float)$inv['total_with_vat'], $inv['invoice_date'], $items_data, (float)$inv['vat_amount']);
    } else {
        recordPurchaseJournal($inv['id'], (float)$inv['total_with_vat'], $inv['invoice_date'], $items_data, (float)$inv['vat_amount']);
    }
    echo "Journaled Invoice #{$inv['id']} ({$inv['type']})\n";
}

// 2. Payments
$payments = $db->query("SELECT p.*, i.type FROM payments p JOIN invoices i ON p.invoice_id = i.id ORDER BY p.id ASC")->fetchAll(PDO::FETCH_ASSOC);
foreach ($payments as $pay) {
    if ($pay['type'] === 'sale') {
        recordPaymentReceivedJournal($pay['id'], (float)$pay['amount'], $pay['payment_date'], $pay['payment_method']);
    } else {
        recordPaymentMadeJournal($pay['id'], (float)$pay['amount'], $pay['payment_date'], $pay['payment_method']);
    }
    echo "Journaled Payment #{$pay['id']} for {$pay['type']} Invoice\n";
}

// 3. Expenses
$expenses = $db->query("SELECT e.*, c.name_en FROM expenses e JOIN expense_categories c ON e.category_id = c.id ORDER BY e.id ASC")->fetchAll(PDO::FETCH_ASSOC);
foreach ($expenses as $exp) {
    recordExpenseJournal($exp['id'], (float)$exp['amount'], $exp['expense_date'], $exp['name_en']);
    echo "Journaled Expense #{$exp['id']}\n";
}

// 4. Payroll
$payrolls = $db->query("SELECT p.*, e.name FROM hr_payroll p JOIN hr_employees e ON p.employee_id = e.id WHERE p.status = 'paid' ORDER BY p.id ASC")->fetchAll(PDO::FETCH_ASSOC);
foreach ($payrolls as $proll) {
    recordPayrollJournal($proll['id'], (float)$proll['net_salary'], $proll['payment_date'] ?? date('Y-m-d'), $proll['name']);
    echo "Journaled Payroll #{$proll['id']} for {$proll['name']}\n";
}

// 5. Returns
$s_returns = $db->query("SELECT * FROM sales_returns ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
foreach ($s_returns as $ret) {
    recordSalesReturnJournal($ret['id'], (float)$ret['total_amount'], $ret['return_date']);
    echo "Journaled Sales Return #{$ret['id']}\n";
}

$p_returns = $db->query("SELECT * FROM purchase_returns ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
foreach ($p_returns as $ret) {
    recordPurchaseReturnJournal($ret['id'], (float)$ret['total_amount'], $ret['return_date']);
    echo "Journaled Purchase Return #{$ret['id']}\n";
}

echo "Migration completed successfully!\n";
