<?php
namespace App\Http\Controllers;
use App\Models as M;
use App\Services\SequenceService;
use App\Support\CrudRegistry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class WeighbridgeTicketController extends Controller {
    public function index(Request $r) { return app(CrudController::class)->index($r, 'weighbridge-tickets'); }
    public function show(int $id) { return app(CrudController::class)->show('weighbridge-tickets', $id); }
    public function create() {
        $this->need('sales.create');
        return view('docs.weighbridge.form', $this->formData(new M\WeighbridgeTicket(['ticket_date' => date('Y-m-d'), 'transaction_type' => 'sales-dispatch'])));
    }
    public function store(Request $r) {
        $this->need('sales.create');
        $d = $r->validate(['ticket_date' => 'required|date', 'vehicle_no' => 'required|max:30', 'driver_name' => 'nullable|max:100',
            'transporter_id' => 'nullable|exists:transporters,id', 'customer_id' => 'nullable|exists:customers,id',
            'supplier_id' => 'nullable|exists:suppliers,id', 'product_id' => 'nullable|exists:products,id',
            'transaction_type' => 'required|in:sales-dispatch,purchase-receipt,internal-transfer', 'sales_order_id' => 'nullable|exists:sales_orders,id',
            'first_weight' => 'required|numeric|min:0', 'first_is' => 'required|in:gross,tare', 'remarks' => 'nullable|max:500']);
        $t = M\WeighbridgeTicket::create([
            'ticket_no' => SequenceService::next('weighbridge'), 'ticket_date' => $d['ticket_date'], 'vehicle_no' => strtoupper($d['vehicle_no']),
            'driver_name' => $d['driver_name'] ?? null, 'transporter_id' => $d['transporter_id'] ?? null, 'customer_id' => $d['customer_id'] ?? null,
            'supplier_id' => $d['supplier_id'] ?? null, 'product_id' => $d['product_id'] ?? null, 'transaction_type' => $d['transaction_type'],
            'sales_order_id' => $d['sales_order_id'] ?? null,
            'gross_weight' => $d['first_is'] === 'gross' ? $d['first_weight'] : 0, 'tare_weight' => $d['first_is'] === 'tare' ? $d['first_weight'] : 0,
            'net_weight' => 0, 'first_weight_time' => now(), 'operator_id' => Auth::id(), 'status' => 'open', 'remarks' => $d['remarks'] ?? null]);
        return redirect()->route('weighbridge-tickets.show', $t)->with('success', 'Ticket '.$t->ticket_no.' opened — capture second weight to close.');
    }
    public function closeForm(int $id) {
        $this->need('sales.edit');
        $t = M\WeighbridgeTicket::findOrFail($id);
        abort_unless($t->status === 'open', 403, 'Ticket is not open.');
        return view('docs.weighbridge.close', ['t' => $t, 'cfg' => CrudRegistry::get('weighbridge-tickets'), 'key' => 'weighbridge-tickets']);
    }
    public function close(Request $r, int $id) {
        $this->need('sales.edit');
        $t = M\WeighbridgeTicket::findOrFail($id);
        abort_unless($t->status === 'open', 403, 'Ticket is not open.');
        $d = $r->validate(['second_weight' => 'required|numeric|min:0']);
        $firstIsGross = $t->gross_weight > 0;
        $gross = $firstIsGross ? $t->gross_weight : $d['second_weight'];
        $tare = $firstIsGross ? $d['second_weight'] : $t->tare_weight;
        $t->update(['gross_weight' => $gross, 'tare_weight' => $tare, 'net_weight' => round(abs($gross - $tare), 3), 'second_weight_time' => now(), 'status' => 'closed']);
        return redirect()->route('weighbridge-tickets.show', $t)->with('success', 'Ticket closed. Net: '.qty($t->net_weight).' t');
    }
    public function destroy(int $id) {
        $this->need('sales.delete');
        $t = M\WeighbridgeTicket::findOrFail($id);
        abort_unless($t->status === 'open', 403, 'Only open tickets can be deleted.');
        $t->delete();
        return redirect()->route('weighbridge-tickets.index')->with('success', 'Ticket deleted.');
    }
    public function print(Request $r, int $id) {
        $this->need('sales.view');
        $doc = M\WeighbridgeTicket::with('customer', 'product', 'transporter')->findOrFail($id);
        if ($r->get('pdf')) return \App\Services\PdfService::download('docs.weighbridge.print', ['t' => $doc], 'WB-'.($doc->ticket_no ?? $id).'.pdf');
        return view('docs.weighbridge.print', ['t' => $doc]);
    }
    protected function formData(M\WeighbridgeTicket $t): array {
        return ['record' => $t, 'isNew' => !$t->exists, 'cfg' => CrudRegistry::get('weighbridge-tickets'), 'key' => 'weighbridge-tickets',
            'docNo' => SequenceService::peek('weighbridge'),
            'customers' => M\Customer::where('is_active', true)->orderBy('name')->get(), 'suppliers' => M\Supplier::where('is_active', true)->orderBy('name')->get(),
            'products' => M\Product::where('is_active', true)->orderBy('name')->get(), 'transporters' => M\Transporter::orderBy('name')->get(),
            'orders' => M\SalesOrder::whereIn('status', ['confirmed', 'partially-dispatched'])->orderByDesc('id')->limit(200)->get()];
    }
}
