<?php

namespace App\Http\Controllers\Accounting;

use App\Http\Controllers\Controller;
use App\Models\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SupplierController extends Controller
{
    /**
     * Display a listing of the suppliers.
     */
    // app/Http/Controllers/SupplierController.php

    public function index()
{
    // CRITICAL: Must use paginate(), NOT get()
    $suppliers = Supplier::where('company_id', Auth::user()->current_company_id)
        ->orderBy('name', 'asc')
        ->paginate(20); 

    return view('suppliers.index', compact('suppliers'));
}
    /**
     * Show the form for creating a new supplier.
     */
    public function create()
    {
        return view('accounting.suppliers.create');
    }

    /**
     * Store a newly created supplier in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:50',
            'tax_id' => 'nullable|string|max:100',
            'physical_address' => 'nullable|string',
            'postal_address' => 'nullable|string',
            'country' => 'nullable|string|max:100',
            'opening_balance' => 'nullable|numeric',
            'contact_first_name' => 'nullable|string|max:100',
            'contact_last_name' => 'nullable|string|max:100',
            'contact_email' => 'nullable|email|max:255',
            'contact_phone' => 'nullable|string|max:50',
            'notes' => 'nullable|string',
        ]);

        $validated['company_id'] = Auth::user()->current_company_id;
        $validated['created_by'] = Auth::id();

        Supplier::create($validated);

        return redirect()->route('accounting.suppliers')
            ->with('success', 'Supplier created successfully.');
    }

    /**
     * Show the form for editing the specified supplier.
     */
    public function edit($id)
    {
        $supplier = Supplier::where('company_id', Auth::user()->current_company_id)
            ->findOrFail($id);

        return view('accounting.suppliers.edit', compact('supplier'));
    }

    /**
     * Update the specified supplier in storage.
     */
    public function update(Request $request, $id)
    {
        $supplier = Supplier::where('company_id', Auth::user()->current_company_id)
            ->findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:50',
            'tax_id' => 'nullable|string|max:100',
            'physical_address' => 'nullable|string',
            'postal_address' => 'nullable|string',
            'country' => 'nullable|string|max:100',
            'contact_first_name' => 'nullable|string|max:100',
            'contact_last_name' => 'nullable|string|max:100',
            'contact_email' => 'nullable|email|max:255',
            'contact_phone' => 'nullable|string|max:50',
            'notes' => 'nullable|string',
        ]);

        // Note: opening_balance is typically excluded from update to maintain audit trail integrity
        $supplier->update($validated);

        return redirect()->route('accounting.suppliers')
            ->with('success', 'Supplier updated successfully.');
    }

    /**
     * Archive (Soft Delete) the specified supplier.
     */
    public function destroy($id)
    {
        $supplier = Supplier::where('company_id', Auth::user()->current_company_id)
            ->findOrFail($id);

        $supplier->delete();

        return redirect()->route('accounting.suppliers')
            ->with('success', 'Supplier archived successfully.');
    }

    /**
     * Display the supplier's ledger/statement.
     */
    public function showStatement($id)
    {
        $companyId = Auth::user()->current_company_id;
        $supplier = Supplier::where('company_id', $companyId)->findOrFail($id);

        // Fetch journal entries linked to this supplier across all posted transactions
        $entries = \App\Models\JournalEntry::where('supplier_id', $id)
            ->with('transaction')
            ->whereHas('transaction', function($query) {
                $query->where('status', 'posted');
            })
            ->get()
            ->sortBy('transaction.transaction_date');

        return view('accounting.suppliers.statement', compact('supplier', 'entries'));
    }

    /**
     * Handle Bulk Actions (Export, Delete, Export All).
     */
    public function bulkAction(Request $request)
    {
        $ids = $request->input('ids', []);
        $action = $request->input('action');
        $companyId = Auth::user()->current_company_id;

        if ($action === 'export_all') {
            $allIds = Supplier::where('company_id', $companyId)->pluck('id')->toArray();
            return $this->exportToCsv($allIds, $companyId);
        }

        if (empty($ids)) {
            return back()->with('warning', 'No suppliers selected.');
        }

        switch ($action) {
            case 'delete':
                Supplier::whereIn('id', $ids)->where('company_id', $companyId)->delete();
                return back()->with('success', count($ids) . ' supplier(s) archived.');

            case 'export':
                return $this->exportToCsv($ids, $companyId);

            default:
                return back()->with('error', 'Unknown action.');
        }
    }

    /**
     * Export selected suppliers to CSV.
     */
    protected function exportToCsv($ids, $companyId)
    {
        $fileName = 'Suppliers_Export_' . now()->format('Y-m-d_His') . '.csv';
        
        $headers = [
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=$fileName",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        ];

        $suppliers = Supplier::whereIn('id', $ids)
            ->where('company_id', $companyId)
            ->get();

        $callback = function() use($suppliers) {
            $file = fopen('php://output', 'w');
            fputcsv($file, [
                'Supplier Name', 'Email', 'Phone', 'Country', 'Physical Address', 
                'Postal Address', 'Contact Person', 'Contact Email', 'Contact Phone', 'Balance'
            ]);

            foreach ($suppliers as $s) {
                fputcsv($file, [
                    $s->name,
                    $s->email,
                    $s->phone,
                    $s->country,
                    $s->physical_address,
                    $s->postal_address,
                    $s->contact_full_name, // Using the Model Accessor
                    $s->contact_email,
                    $s->contact_phone,
                    $s->opening_balance
                ]);
            }
            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}