<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Tax;
use App\Models\Currency;
use App\Models\DocumentHeader;
use App\Models\SupplierDocumentHeader;
use Carbon\Carbon;
use PDF;

class TaxReportController extends Controller
{
    // Display initial form
    public function index()
    {
        $taxes = Tax::all();
        $currencies = Currency::all();
        
        return view('reports.tax-report', compact('taxes', 'currencies'));
    }

    // Generate tax report
    public function generate(Request $request)
    {
        $request->validate([
            'tax' => 'required',
            'pfrom' => 'required|date',
            'pto' => 'required|date',
            'from' => 'required|date',
            'to' => 'required|date',
            'curr' => 'required|exists:currencies,id',
        ]);

        $taxId = $request->tax;
        $pfrom = $request->pfrom;
        $pto = $request->pto;
        $from = $request->from;
        $to = $request->to;
        $currencyId = $request->curr;

        $currency = Currency::find($currencyId);
        $currnames = $currency ? $currency->name : '';

        $taxDetails = null;
        if ($taxId !== 'All') {
            $taxDetails = Tax::find($taxId);
        }

        $outputTransactions = $this->getOutputTaxTransactions($taxId, $pfrom, $pto, $from, $to);
        $inputTransactions = $this->getInputTaxTransactions($taxId, $pfrom, $pto, $from, $to);

        $outputTotals = $this->calculateTotals($outputTransactions);
        $inputTotals = $this->calculateTotals($inputTransactions);

        // Pass only defined variables to view
        $currencies = Currency::all();
        $taxes = Tax::all();

        return view('reports.tax-report', compact(
            'taxes',
            'currencies',
            'outputTransactions',
            'inputTransactions',
            'outputTotals',
            'inputTotals',
            'taxId',
            'pfrom',
            'pto',
            'from',
            'to',
            'currencyId',
            'currnames',
            'taxDetails'
        ));
    }

    private function getOutputTaxTransactions($taxId, $pfrom, $pto, $from, $to)
    {
        $query = DocumentHeader::with(['lines', 'customer'])
            ->whereBetween('document_date', [$pfrom, $pto])
            ->whereBetween('created_at', [$from, $to])
            ->whereIn('type', ['invoice', 'credit_note', 'debit_note']); // Updated to only include these types

        if ($taxId !== 'All') {
            $query->whereHas('lines', function($q) use ($taxId) {
                $q->where('tax_id', $taxId);
            });
        }

        return $query->get();
    }

    private function getInputTaxTransactions($taxId, $pfrom, $pto, $from, $to)
    {
        $query = SupplierDocumentHeader::with(['lines', 'supplier'])
            ->whereBetween('document_date', [$pfrom, $pto])
            ->whereBetween('created_at', [$from, $to])
            ->whereIn('type', ['returns_debit', 'sales_invoice', 'credit_supplier']); // Updated to only include these types

        if ($taxId !== 'All') {
            $query->whereHas('lines', function($q) use ($taxId) {
                $q->where('tax_id', $taxId);
            });
        }

        return $query->get();
    }

    private function calculateTotals($transactions)
    {
        $totals = [
            'invoice' => 0,
            'tax' => 0,
            'incl' => 0,
        ];

        foreach ($transactions as $transaction) {
            foreach ($transaction->lines as $line) {
                $invoiceAmount = $line->price * $line->quantity;
                $taxAmount = $invoiceAmount * ($line->tax_rate / 100);
                $amountIncl = $invoiceAmount + $taxAmount;

                $totals['invoice'] += $invoiceAmount;
                $totals['tax'] += $taxAmount;
                $totals['incl'] += $amountIncl;
            }
        }

        return $totals;
    }

    public function downloadPdf(Request $request)
    {
        $data = $request->all();

        $outputTransactions = $this->getOutputTaxTransactions(
            $data['taxId'], 
            $data['pfrom'], 
            $data['pto'], 
            $data['from'], 
            $data['to']
        );

        $inputTransactions = $this->getInputTaxTransactions(
            $data['taxId'], 
            $data['pfrom'], 
            $data['pto'], 
            $data['from'], 
            $data['to']
        );

        $outputTotals = $this->calculateTotals($outputTransactions);
        $inputTotals = $this->calculateTotals($inputTransactions);

        $currency = Currency::find($data['currencyId']);
        $currnames = $currency ? $currency->name : '';

        $taxDetails = null;
        if ($data['taxId'] !== 'All') {
            $taxDetails = Tax::find($data['taxId']);
        }

        $pdf = PDF::loadView('reports.tax-report-pdf', compact(
            'outputTransactions',
            'inputTransactions',
            'outputTotals',
            'inputTotals',
            'data',
            'currnames',
            'taxDetails'
        ));

        return $pdf->download('tax-report-'.Carbon::now()->format('Y-m-d').'.pdf');
    }
}