<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\SupplierAccount;
use App\Models\Currency;
use App\Models\SupplierDocumentHeader;
use App\Models\CompanySettings;
use App\Models\SupplierDocumentLine;
use App\Models\PriceListingSetup;
use App\Models\GeneralLedger;
use App\Models\Warehouse;
use App\Models\Project;
use App\Models\Tax;
use App\Models\Uom;
use App\Models\SupplierDocumentSetting;
use App\Models\WarehouseTransfer;
use App\Models\WarehouseTransferLine;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf as PDF;
use Illuminate\Support\Str;

class SupplierDocumentReprintController extends Controller
{
    // Display initial form
    public function index()
    {
        $suppliers = SupplierAccount::orderBy('supplier_code')->get();
        $currencies = Currency::orderBy('code')->get();
        
        return view('reports.supplier-document-reprint', compact('suppliers', 'currencies'));
    }

    // Generate supplier document reprint report
    public function generate(Request $request)
    {
        $request->validate([
            'supplier_account' => 'required',
            'date_from' => 'required|date',
            'date_to' => 'required|date|after_or_equal:date_from',
            'currency' => 'required',
        ]);

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

        $suppliers  = SupplierAccount::orderBy('supplier_code')->get();
        $currencies = Currency::orderBy('code')->get();

        // Handle "All Suppliers"
        if ($supplierId == 'all') {
            $allDocuments  = [];
            $suppliersList = SupplierAccount::orderBy('supplier_code')->get();

            foreach ($suppliersList as $supplier) {
                $documents = $this->getDocuments($supplier->id, $currencyCode, $dateFrom, $dateTo);

                $allDocuments[] = [
                    'supplier'  => $supplier,
                    'documents' => $documents,
                ];
            }

            return view('reports.supplier-document-reprint', compact(
                'allDocuments',
                'supplierId',
                'dateFrom',
                'dateTo',
                'currencyCode',
                'suppliers',
                'currencies',
                'company'
            ));
        } else {
            // Single supplier
            $supplier  = SupplierAccount::findOrFail($supplierId);
            $documents = $this->getDocuments($supplierId, $currencyCode, $dateFrom, $dateTo);

            return view('reports.supplier-document-reprint', compact(
                'documents',
                'supplierId',
                'dateFrom',
                'dateTo',
                'currencyCode',
                'suppliers',
                'currencies',
                'company',
                'supplier'
            ));
        }
    }

    // Retrieve supplier documents
    private function getDocuments($supplierId, $currencyCode, $dateFrom, $dateTo)
    {
        return SupplierDocumentHeader::with('supplier')
            ->where('supplier_account_id', $supplierId)
            ->where('currency_code', $currencyCode)
            ->whereBetween('document_date', [$dateFrom, $dateTo])
            ->orderBy('document_date')
            ->get();
    }

    // Reprint a specific supplier document
    public function reprintDocument($id)
    {
        $document = SupplierDocumentHeader::with(['supplier', 'lines'])->findOrFail($id);
        $company  = CompanySettings::first();
        
        // Set flag to indicate this is a reprint
        $isReprint = true;
        
        return view('documents.supplier.pdf', compact('document', 'company', 'isReprint'));
    }

    // Download PDF of a specific supplier document
    public function downloadDocument($id)
    {
        $document = SupplierDocumentHeader::with(['supplier', 'lines'])->findOrFail($id);
        $company  = CompanySettings::first();
        $isReprint = true;
        
        $pdf = PDF::loadView('documents.supplier.pdf', compact('document', 'company', 'isReprint'));
        return $pdf->download("COPY - {$document->document_number}.pdf");
    }

    // ====== NEW METHODS ADDED ======

    public function pdf(SupplierDocumentHeader $document)
    {
        return view('documents.supplier.pdf', [
            'document'      => $document,
            'company'       => CompanySettings::first(),
            'pricingType'   => $document->pricing_type,
            'prefix'        => $this->getDefaultPrefix($document->type),
            'documentTitle' => $this->getDocumentTitle($document->type),
            'preview'       => true, // Add preview flag
        ]);
    }

    public function deliveryNotePreview(SupplierDocumentHeader $document)
    {
        return view('documents.supplier.delivery_note', [
            'document' => $document,
            'company'  => CompanySettings::first(),
            'preview'  => true
        ]);
    }

    public function invoicePreview(SupplierDocumentHeader $document)
    {
        return view('documents.supplier.pdf', [
            'document'      => $document,
            'company'       => CompanySettings::first(),
            'pricingType'   => $document->pricing_type,
            'prefix'        => $this->getDefaultPrefix($document->type),
            'documentTitle' => $this->getDocumentTitle($document->type),
            'preview'       => true, // Add preview flag
        ]);
    }

    // ====== HELPER METHODS ======
    private function getDefaultPrefix($type)
    {
        // Example: implement logic to return prefix based on type
        return strtoupper(substr($type, 0, 3));
    }

    private function getDocumentTitle($type)
    {
        // Example: implement logic to return readable title
        return ucfirst($type) . " Document";
    }
}
