<?php
/**
 * Ghalla Mandi ERP — Seed Some Transactions for Testing (FIXED)
 */

header('Content-Type: text/plain; charset=utf-8');
require_once __DIR__ . '/../api/config/database.php';
require_once __DIR__ . '/../api/helpers/UUID.php';
require_once __DIR__ . '/../api/services/AccountingService.php';

try {
    $db = Database::connect();

    echo "Adding Sample Transactions...\n";

    // 1. Get some IDs
    $zamidarId = $db->query("SELECT id FROM accounts WHERE type = 'party' AND sub_type = 'zamidar' LIMIT 1")->fetchColumn();
    $khareedarId = $db->query("SELECT id FROM accounts WHERE type = 'party' AND sub_type = 'khareedar' LIMIT 1")->fetchColumn();
    $itemId = $db->query("SELECT id FROM items LIMIT 1")->fetchColumn();
    $cashId = $db->query("SELECT id FROM accounts WHERE type = 'bank_cash' AND sub_type = 'cash' LIMIT 1")->fetchColumn();
    $adminId = 1;

    $systemAccounts = [];
    foreach ($db->query("SELECT id, sub_type FROM accounts WHERE is_system = 1")->fetchAll() as $row) {
        $systemAccounts[$row['sub_type']] = (int)$row['id'];
    }

    // 2. Create a Purchase (Katchi Parchi)
    echo "Creating a Purchase...\n";
    $db->beginTransaction();
    
    $p_uuid = UUID::generate();
    $voucherNo = "خ-" . mt_rand(5000, 9999);
    $lotNo = "L-" . mt_rand(5000, 9999);
    $date = date('Y-m-d');

    $db->prepare("
        INSERT INTO purchase_master (uuid, voucher_no, voucher_date, zamidar_id, item_id, gross_weight, net_weight, rate, gross_amount, net_payable, created_by)
        VALUES (?,?,?,?,?,?,?,?,?,?,?)
    ")->execute([$p_uuid, $voucherNo, $date, $zamidarId, $itemId, 400, 390, 4500, 43875, 43000, $adminId]);
    
    $purchaseId = $db->lastInsertId();

    $db->prepare("INSERT INTO purchase_lots (purchase_id, lot_number, item_id, zamidar_id, net_weight, remaining_qty) VALUES (?,?,?,?,?,?)")
       ->execute([$purchaseId, $lotNo, $itemId, $zamidarId, 390, 390]);
    
    $lotId = $db->lastInsertId(); // Store lotId properly

    // Journal for Purchase
    AccountingService::postJournal($db, [
        'date' => $date, 'source_type' => 'purchase', 'source_id' => $purchaseId, 'narration' => "خرید پرچی {$voucherNo}", 'created_by' => $adminId
    ], [
        ['account_id' => $systemAccounts['purchase'], 'debit' => 43875, 'credit' => 0],
        ['account_id' => $zamidarId, 'debit' => 0, 'credit' => 43000],
        ['account_id' => $systemAccounts['mazdoori'], 'debit' => 0, 'credit' => 875]
    ]);

    // 3. Create a Sale (Pakki Parchi)
    echo "Creating a Sale...\n";
    $s_uuid = UUID::generate();
    $sVoucherNo = "ب-" . mt_rand(5000, 9999);
    
    $db->prepare("
        INSERT INTO sale_master (uuid, voucher_no, voucher_date, khareedar_id, lot_id, item_id, sale_weight, rate, gross_amount, net_receivable, created_by)
        VALUES (?,?,?,?,?,?,?,?,?,?,?)
    ")->execute([$s_uuid, $sVoucherNo, $date, $khareedarId, $lotId, $itemId, 100, 4500, 11250, 11500, $adminId]);
    
    $saleId = $db->lastInsertId();
    
    // Update Inventory
    $db->prepare("UPDATE purchase_lots SET remaining_qty = remaining_qty - 100, status = 'partial' WHERE id = ?")->execute([$lotId]);

    // Journal for Sale
    AccountingService::postJournal($db, [
        'date' => $date, 'source_type' => 'sale', 'source_id' => $saleId, 'narration' => "فروخت پرچی {$sVoucherNo}", 'created_by' => $adminId
    ], [
        ['account_id' => $khareedarId, 'debit' => 11500, 'credit' => 0],
        ['account_id' => $systemAccounts['sale'], 'debit' => 0, 'credit' => 11250],
        ['account_id' => $systemAccounts['commission'], 'debit' => 0, 'credit' => 250]
    ]);

    $db->commit();
    echo "\nSUCCESS! Sample purchase and sale transactions added.\n";

} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) $db->rollBack();
    echo "ERROR: " . $e->getMessage() . "\n";
}
