<?php

namespace App\Http\Controllers;

use App\Models\DeliveryNote;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Yajra\DataTables\Facades\DataTables;

class DeliveryNoteController extends Controller
{
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = DeliveryNote::query()
                ->with(['purchaseOrder'])
                ->select('delivery_notes.*');

            return DataTables::of($query)
                ->addColumn('po_number', function (DeliveryNote $dn) {
                    return $dn->purchaseOrder->po_number;
                })
                ->editColumn('delivery_date', function (DeliveryNote $dn) {
                    return $dn->delivery_date->format('Y-m-d');
                })
                ->editColumn('status', function (DeliveryNote $dn) {
                    $statusColors = [
                        'pending' => 'secondary',
                        'completed' => 'success',
                        'cancelled' => 'danger'
                    ];
                    $color = $statusColors[$dn->status] ?? 'secondary';
                    return '<span class="badge bg-' . $color . '">' . ucfirst($dn->status) . '</span>';
                })
                ->addColumn('actions', function (DeliveryNote $dn) {
                    return '<a href="' . route('delivery-notes.show', $dn) . '" class="btn btn-sm btn-primary">View</a>';
                })
                ->rawColumns(['status', 'actions'])
                ->toJson();
        }

        return view('delivery_notes.index');
    }

    public function show(DeliveryNote $deliveryNote): View
    {
        $deliveryNote->load(['purchaseOrder.items']);
        return view('delivery_notes.show', compact('deliveryNote'));
    }
}
