<?php

namespace App\Imports;

use App\Models\Account;
use App\Models\JournalEntry;
use App\Models\JournalEntryLine;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Illuminate\Support\Facades\DB;

class OpeningBalanceImport implements ToCollection, WithHeadingRow
{
    public function collection(Collection $rows)
    {
        if ($rows->isEmpty()) return;

        // Try to get date and partner from the first row if available
        $firstRow = $rows->first();
        
        // Parse Date
        $date = now()->format('Y-m-d');
        if (!empty($firstRow['date'])) {
            try {
                if (is_numeric($firstRow['date'])) {
                    $date = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($firstRow['date'])->format('Y-m-d');
                } else {
                    $date = \Carbon\Carbon::parse($firstRow['date'])->format('Y-m-d');
                }
            } catch (\Exception $e) {
                // Keep default date
            }
        }

        // Parse Partner
        $partnerId = null;
        if (!empty($firstRow['partner_name'])) {
            $partner = \App\Models\Partner::where('name', 'like', trim($firstRow['partner_name']))->first();
            if ($partner) {
                $partnerId = $partner->id;
            }
        }

        $branchId = auth()->user()->branch_id ?? 1;

        $entry = JournalEntry::create([
            'entry_number' => JournalEntry::generateEntryNumber(),
            'date' => $date,
            'description' => 'Imported Opening Balances',
            'reference' => 'IMPORT-OB-' . time(),
            'status' => 'draft',
            'partner_id' => $partnerId,
            'branch_id' => $branchId,
            'created_by' => auth()->id(),
        ]);

        foreach ($rows as $row) {
            if (empty($row['account_code'])) continue;

            $account = Account::where('code', $row['account_code'])->first();
            if (!$account) continue;

            $debit = floatval($row['debit'] ?? 0);
            $credit = floatval($row['credit'] ?? 0);

            if ($debit == 0 && $credit == 0) continue;

            JournalEntryLine::create([
                'journal_entry_id' => $entry->id,
                'account_id' => $account->id,
                'description' => $row['description'] ?? 'Opening Balance',
                'debit' => $debit,
                'credit' => $credit,
            ]);
        }
    }
}
