<?php

namespace App\Livewire\Reports;

use App\Models\Ledger;
use App\Models\Party;
use App\Models\Page;
use App\Models\Setting;
use Livewire\Component;
use Livewire\Attributes\Layout;

#[Layout('layouts.app')]
class PagesReport extends Component
{
    public $ledger_id = '';
    public $party_id = '';
    
    public $columns = [
        'ledger' => true,
        'page_number' => true,
        'code' => true,
        'name' => true,
        'debit_account' => true,
        'credit_account' => true,
        'description' => true,
        'is_active' => true,
        'created_at' => true,
    ];

    public function toggleColumn($column)
    {
        if (array_key_exists($column, $this->columns)) {
            $this->columns[$column] = !$this->columns[$column];
        }
    }

    public function render()
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $ledgers = Ledger::orderBy('name')->get();
        $parties = Party::orderBy('name')->get();
        
        $query = Page::with(['ledger', 'debitAccount', 'creditAccount'])->orderBy('id', 'asc');
        
        if ($this->ledger_id) {
            $query->where('ledger_id', $this->ledger_id);
        }
        
        if ($this->party_id) {
            $query->where(function($q) {
                $q->whereHas('ledger.account', function($sq) {
                    $sq->where('party_id', $this->party_id);
                })
                ->orWhereHas('debitAccount', function($sq) {
                    $sq->where('party_id', $this->party_id);
                })
                ->orWhereHas('creditAccount', function($sq) {
                    $sq->where('party_id', $this->party_id);
                });
            });
        }
        
        $pages = $query->get();
        $settings = Setting::pluck('value', 'key')->toArray();

        return view('livewire.reports.pages-report', [
            'pages' => $pages,
            'ledgers' => $ledgers,
            'parties' => $parties,
            'settings' => $settings,
        ]);
    }
}
