<?php

namespace App\Http\Controllers;

use App\Models\Entity;
use App\Models\Setting;
use Illuminate\Http\Request;

class PrintReportController extends Controller
{
    public function entities(Request $request)
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $columns = $request->input('columns', []);
        if (empty($columns)) {
            // Default all if none specified
            $columns = [
                'code' => '1', 'name' => '1', 'short_name' => '1', 'commercial_record' => '1',
                'unified_number' => '1', 'tax_number' => '1', 'address' => '1', 'notes' => '1',
                'is_active' => '1', 'created_at' => '1'
            ];
        }

        $entities = Entity::orderBy('id', 'asc')->get();
        $settings = Setting::pluck('value', 'key')->toArray();

        return view('reports.print.entities', compact('entities', 'settings', 'columns'));
    }

    public function branches(Request $request)
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $columns = $request->input('columns', []);
        if (empty($columns)) {
            $columns = [
                'entity' => '1', 'code' => '1', 'name' => '1', 'short_name' => '1', 
                'commercial_record' => '1', 'tax_number' => '1', 'phone' => '1', 
                'address' => '1', 'notes' => '1', 'is_active' => '1', 'created_at' => '1'
            ];
        }

        $entityId = $request->input('entity_id');
        $query = \App\Models\Branch::with('entity')->orderBy('id', 'asc');
        
        $entityName = null;
        if ($entityId) {
            $query->where('entity_id', $entityId);
            $entityName = Entity::find($entityId)?->name;
        }

        $branches = $query->get();
        $settings = Setting::pluck('value', 'key')->toArray();

        return view('reports.print.branches', compact('branches', 'settings', 'columns', 'entityName'));
    }

    public function centers(Request $request)
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $columns = $request->input('columns', []);
        if (empty($columns)) {
            $columns = [
                'entity' => '1', 'branch' => '1', 'code' => '1', 'name' => '1',
                'address' => '1', 'notes' => '1', 'is_active' => '1', 'created_at' => '1'
            ];
        }

        $entityId = $request->input('entity_id');
        $branchId = $request->input('branch_id');
        
        $query = \App\Models\Center::with('branch.entity')->orderBy('id', 'asc');
        
        $entityName = null;
        $branchName = null;
        
        if ($branchId) {
            $query->where('branch_id', $branchId);
            $branch = \App\Models\Branch::with('entity')->find($branchId);
            if ($branch) {
                $branchName = $branch->name;
                $entityName = $branch->entity?->name;
            }
        } elseif ($entityId) {
            $query->whereHas('branch', function ($q) use ($entityId) {
                $q->where('entity_id', $entityId);
            });
            $entityName = Entity::find($entityId)?->name;
        }

        $centers = $query->get();
        $settings = Setting::pluck('value', 'key')->toArray();

        return view('reports.print.centers', compact('centers', 'settings', 'columns', 'entityName', 'branchName'));
    }

    public function projects(Request $request)
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $columns = $request->input('columns', []);
        if (empty($columns)) {
            $columns = [
                'entity' => '1', 'branch' => '1', 'center' => '1', 'code' => '1', 'name' => '1',
                'description' => '1', 'is_active' => '1', 'created_at' => '1'
            ];
        }

        $entityId = $request->input('entity_id');
        $branchId = $request->input('branch_id');
        $centerId = $request->input('center_id');
        
        $query = \App\Models\Project::with(['entity', 'branch', 'center'])->orderBy('id', 'asc');
        
        $entityName = null;
        $branchName = null;
        $centerName = null;
        
        if ($centerId) {
            $query->where('center_id', $centerId);
            $center = \App\Models\Center::with('branch.entity')->find($centerId);
            if ($center) {
                $centerName = $center->name;
                $branchName = $center->branch?->name;
                $entityName = $center->branch?->entity?->name;
            }
        } elseif ($branchId) {
            $query->where('branch_id', $branchId);
            $branch = \App\Models\Branch::with('entity')->find($branchId);
            if ($branch) {
                $branchName = $branch->name;
                $entityName = $branch->entity?->name;
            }
        } elseif ($entityId) {
            $query->where('entity_id', $entityId);
            $entityName = Entity::find($entityId)?->name;
        }

        $projects = $query->get();
        $settings = Setting::pluck('value', 'key')->toArray();

        return view('reports.print.projects', compact('projects', 'settings', 'columns', 'entityName', 'branchName', 'centerName'));
    }

    public function parties(Request $request)
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $columns = $request->input('columns', []);
        if (empty($columns)) {
            $columns = [
                'code' => '1', 'name' => '1', 'document_number' => '1', 'tax_number' => '1',
                'phone' => '1', 'is_active' => '1', 'created_at' => '1'
            ];
        }

        $parties = \App\Models\Party::orderBy('id', 'asc')->get();
        $settings = Setting::pluck('value', 'key')->toArray();

        return view('reports.print.parties', compact('parties', 'settings', 'columns'));
    }

    public function accounts(Request $request)
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $columns = $request->input('columns', []);
        if (empty($columns)) {
            $columns = [
                'party' => '1', 'currency' => '1', 'account_number' => '1', 'name' => '1',
                'notes' => '1', 'is_active' => '1', 'created_at' => '1'
            ];
        }

        $partyId = $request->input('party_id');
        
        $query = \App\Models\Account::with(['party', 'currency'])->orderBy('id', 'asc');
        
        $partyName = null;
        
        if ($partyId) {
            $query->where('party_id', $partyId);
            $partyName = \App\Models\Party::find($partyId)?->name;
        }

        $accounts = $query->get();
        $settings = Setting::pluck('value', 'key')->toArray();

        return view('reports.print.accounts', compact('accounts', 'settings', 'columns', 'partyName'));
    }

    public function ledgers(Request $request)
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $columns = $request->input('columns', []);
        if (empty($columns)) {
            $columns = [
                'account' => '1', 'ledger_number' => '1', 'code' => '1', 'name' => '1',
                'description' => '1', 'is_active' => '1', 'created_at' => '1'
            ];
        }

        $entityId = $request->input('entity_id');
        $branchId = $request->input('branch_id');
        $centerId = $request->input('center_id');
        $projectId = $request->input('project_id');
        $partyId = $request->input('party_id');
        $accountId = $request->input('account_id');
        
        $query = \App\Models\Ledger::with(['entity', 'branch', 'center', 'project', 'account.party'])->orderBy('id', 'asc');
        
        $entityName = null;
        $branchName = null;
        $centerName = null;
        $projectName = null;
        $partyName = null;
        $accountName = null;
        
        if ($projectId) {
            $query->where('project_id', $projectId);
            $projectName = \App\Models\Project::find($projectId)?->name;
        } elseif ($centerId) {
            $query->where('center_id', $centerId);
            $centerName = \App\Models\Center::find($centerId)?->name;
        } elseif ($branchId) {
            $query->where('branch_id', $branchId);
            $branchName = \App\Models\Branch::find($branchId)?->name;
        } elseif ($entityId) {
            $query->where('entity_id', $entityId);
            $entityName = \App\Models\Entity::find($entityId)?->name;
        }
        
        if ($accountId) {
            $query->where('account_id', $accountId);
            $accountName = \App\Models\Account::find($accountId)?->name;
        } elseif ($partyId) {
            $query->whereHas('account', function($q) use ($partyId) {
                $q->where('party_id', $partyId);
            });
            $partyName = \App\Models\Party::find($partyId)?->name;
        }

        $ledgers = $query->get();
        $settings = Setting::pluck('value', 'key')->toArray();

        return view('reports.print.ledgers', compact(
            'ledgers', 'settings', 'columns', 
            'entityName', 'branchName', 'centerName', 
            'projectName', 'partyName', 'accountName'
        ));
    }

    public function pages(Request $request)
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $columns = $request->input('columns', []);
        if (empty($columns)) {
            $columns = [
                'ledger' => '1', 'page_number' => '1', 'code' => '1', 'name' => '1',
                'debit_account' => '1', 'credit_account' => '1', 'description' => '1', 
                'is_active' => '1', 'created_at' => '1'
            ];
        }

        $ledgerId = $request->input('ledger_id');
        $partyId = $request->input('party_id');
        
        $query = \App\Models\Page::with(['ledger', 'debitAccount', 'creditAccount'])->orderBy('id', 'asc');
        
        $ledgerName = null;
        $partyName = null;
        
        if ($ledgerId) {
            $query->where('ledger_id', $ledgerId);
            $ledgerName = \App\Models\Ledger::find($ledgerId)?->name;
        }
        
        if ($partyId) {
            $query->where(function($q) use ($partyId) {
                $q->whereHas('ledger.account', function($sq) use ($partyId) {
                    $sq->where('party_id', $partyId);
                })
                ->orWhereHas('debitAccount', function($sq) use ($partyId) {
                    $sq->where('party_id', $partyId);
                })
                ->orWhereHas('creditAccount', function($sq) use ($partyId) {
                    $sq->where('party_id', $partyId);
                });
            });
            $partyName = \App\Models\Party::find($partyId)?->name;
        }

        $pages = $query->get();
        $settings = Setting::pluck('value', 'key')->toArray();

        return view('reports.print.pages', compact(
            'pages', 'settings', 'columns', 'ledgerName', 'partyName'
        ));
    }

    public function balances(Request $request)
    {
        if (!auth()->user()->can('view records')) {
            abort(403);
        }

        $columns = $request->input('columns', []);
        if (empty($columns)) {
            $columns = [
                'account' => '1', 'ledger' => '1', 'page' => '1', 'total_debit' => '1',
                'total_credit' => '1', 'balance' => '1', 'status' => '1'
            ];
        }

        $partyId = $request->input('party_id');
        $accountId = $request->input('account_id');
        $ledgerId = $request->input('ledger_id');
        
        $query = \App\Models\Page::with(['ledger.account', 'transactions'])->orderBy('id', 'asc');
        
        $partyName = null;
        $accountName = null;
        $ledgerName = null;
        
        if ($ledgerId) {
            $query->where('ledger_id', $ledgerId);
            $ledgerName = \App\Models\Ledger::find($ledgerId)?->name;
        } elseif ($accountId) {
            $query->whereHas('ledger', function($q) use ($accountId) {
                $q->where('account_id', $accountId);
            });
            $accountName = \App\Models\Account::find($accountId)?->name;
        } elseif ($partyId) {
            $query->whereHas('ledger.account', function($q) use ($partyId) {
                $q->where('party_id', $partyId);
            });
            $partyName = \App\Models\Party::find($partyId)?->name;
        }

        $pages = $query->get()->map(function($page) {
            $totalDebit = $page->transactions->where('is_active', true)->sum('debit_amount');
            $totalCredit = $page->transactions->where('is_active', true)->sum('credit_amount');
            $balance = $totalDebit - $totalCredit;
            
            $page->total_debit = $totalDebit;
            $page->total_credit = $totalCredit;
            $page->balance = $balance;
            
            return $page;
        });
        
        $sumDebit = $pages->sum('total_debit');
        $sumCredit = $pages->sum('total_credit');
        $sumBalance = $sumDebit - $sumCredit;

        $settings = Setting::pluck('value', 'key')->toArray();

        return view('reports.print.balances', compact(
            'pages', 'settings', 'columns', 'partyName', 'accountName', 'ledgerName',
            'sumDebit', 'sumCredit', 'sumBalance'
        ));
    }
}
