<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Cashbook;
use App\Models\Currency;
use App\Models\CashbookEntry;
use App\Models\CompanySettings;
use App\Models\GeneralLedger;
use PDF;

class CashbookDailyTransactionController extends Controller
{
    // Display initial form
    public function index()
    {
        $cashbooks = Cashbook::with('generalLedger')->orderBy('code')->get();
        $currencies = Currency::orderBy('code')->get();
        
        return view('reports.cashbook-daily-transaction', compact('cashbooks', 'currencies'));
    }

    // Generate cashbook daily transaction report
    public function generate(Request $request)
    {
        $request->validate([
            'cashbook_account' => 'required',
            'date_from' => 'required|date',
            'date_to' => 'required|date|after_or_equal:date_from',
            'currency' => 'required',
        ]);

        $cashbookId = $request->cashbook_account;
        $dateFrom = $request->date_from;
        $dateTo = $request->date_to;
        $currencyCode = $request->currency;
        $company = CompanySettings::first();

        $cashbooks = Cashbook::with('generalLedger')->orderBy('code')->get();
        $currencies = Currency::orderBy('code')->get();

        // Get transaction data
        $transactionData = $this->getTransactionData($cashbookId, $currencyCode, $dateFrom, $dateTo);
        
        // Get cashbook details
        $cashbook = Cashbook::with('generalLedger')->find($cashbookId);

        return view('reports.cashbook-daily-transaction', compact(
            'transactionData',
            'cashbookId',
            'dateFrom',
            'dateTo',
            'currencyCode',
            'cashbooks',
            'currencies',
            'company',
            'cashbook'
        ));
    }

    // Download PDF
    public function downloadPdf(Request $request)
    {
        $request->validate([
            'cashbook_account' => 'required',
            'date_from' => 'required|date',
            'date_to' => 'required|date|after_or_equal:date_from',
            'currency' => 'required',
        ]);

        $cashbookId = $request->cashbook_account;
        $dateFrom = $request->date_from;
        $dateTo = $request->date_to;
        $currencyCode = $request->currency;
        $currency = Currency::where('code', $currencyCode)->first();
        $company = CompanySettings::first();

        // Get transaction data
        $transactionData = $this->getTransactionData($cashbookId, $currencyCode, $dateFrom, $dateTo);
        
        // Get cashbook details
        $cashbook = Cashbook::with('generalLedger')->find($cashbookId);

        $pdf = PDF::loadView('reports.cashbook-daily-transaction-pdf', compact(
            'transactionData',
            'dateFrom',
            'dateTo',
            'currency',
            'company',
            'cashbook'
        ));

        return $pdf->download('cashbook-daily-transactions-' . $cashbook->code . '.pdf');
    }

    // Retrieve transaction data
    private function getTransactionData($cashbookId, $currencyCode, $dateFrom, $dateTo)
    {
        $transactionData = [];
        $balance = 0;

        // Get cashbook entries with GL account information
        $entries = CashbookEntry::with(['currency', 'account'])
            ->where('cashbook_id', $cashbookId)
            ->whereHas('currency', function($query) use ($currencyCode) {
                $query->where('code', $currencyCode);
            })
            ->whereBetween('date', [$dateFrom, $dateTo])
            ->orderBy('date')
            ->get();

        foreach ($entries as $entry) {
            $dr = $entry->dr_amount ?? 0;
            $cr = $entry->cr_amount ?? 0;
            $balance += ($dr - $cr);

            $transactionData[] = [
                'date'        => $entry->date,
                'description' => $entry->description,
                'reference'   => $this->getReference($entry),
                'dr'          => $dr,
                'cr'          => $cr,
                'balance'     => $balance
            ];
        }

        return $transactionData;
    }

    // Format reference based on entry type
    private function getReference($entry)
    {
        // For GL transactions, show the GL account code and name
        if ($entry->module === 'GL' && $entry->account_type === 'App\Models\GeneralLedger') {
            $glAccount = GeneralLedger::find($entry->account_id);
            if ($glAccount) {
                return $glAccount->code . ' - ' . $glAccount->account_name;
            }
        }
        
        if ($entry->reference_type && $entry->reference_id) {
            return $entry->reference_type . ' #' . $entry->reference_id;
        }
        
        if ($entry->cashbook_id) {
            return 'CB' . str_pad($entry->cashbook_id, 3, '0', STR_PAD_LEFT);
        }
        
        return 'N/A';
    }
}