<?php
# ────────────── lee_gwena ──────────────
# Code by: ashley_gwena
# Created: 2026-03-12
# Notes: Export chart of accounts to CSV or Excel
# ───────────────────────────────────────

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\MainAccount;
use Symfony\Component\HttpFoundation\StreamedResponse;

class COAExportController extends Controller
{
    public function index()
    {
        return view('chart_of_accounts.export.index');
    }

    public function exportCSV(): StreamedResponse
    {
        $accounts = MainAccount::query()->with('accountType', 'parent', 'department')->orderBy('account_code')->get();

        return response()->streamDownload(function () use ($accounts) {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, [
                'account_code',
                'account_name',
                'parent_account',
                'account_type',
                'department',
                'is_control_account',
                'is_trust_account',
                'is_active',
                'created_at',
                'updated_at',
                'created_by',
                'updated_by',
            ]);

            foreach ($accounts as $account) {
                fputcsv($handle, [
                    $account->account_code,
                    $account->account_name,
                    $account->parent?->account_code,
                    $account->accountType?->name,
                    $account->department?->name,
                    $account->is_control_account,
                    $account->is_trust_account,
                    $account->is_active,
                    $account->created_at,
                    $account->updated_at,
                    $account->created_by,
                    $account->updated_by,
                ]);
            }

            fclose($handle);
        }, 'chart_of_accounts.csv');
    }

    public function exportExcel(): StreamedResponse
    {
        return $this->exportCSV();
    }
}
