<?php

namespace App\Http\Controllers\Admin\Branch\Bagging;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\Bag;
use App\Models\BagItem;
use App\Models\Parcel;
use Illuminate\Http\Request;

class BaggingController extends Controller
{
    public function index()
    {
        $branches = Branch::all();
        // Load recent bags with parcels; destination is not used in current model
        $bags = Bag::with('parcels')->latest()->take(10)->get();

        return view('admin.branch.bagging.index', compact('branches', 'bags'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'destination_branch_id' => 'nullable|exists:branches,id',
            'parcels' => 'required|string',
        ]);

        // Split lines robustly and remove empty entries
        $trackingNumbers = array_values(array_filter(array_map('trim', preg_split("/\r\n|\n|\r/", $request->parcels))));

        if (empty($trackingNumbers)) {
            return back()->with('error', 'Please provide at least one tracking number.');
        }

        // Find parcels by tracking_id
        $parcels = Parcel::whereIn('tracking_id', $trackingNumbers)->get();
        if ($parcels->isEmpty()) {
            return back()->withErrors(['parcels' => 'No parcels matched the provided tracking IDs.']);
        }

        // Generate a unique bag number and create bag
        do {
            $bagNumber = 'BAG' . mt_rand(100000, 999999);
        } while (Bag::where('bag_number', $bagNumber)->exists());

        $bag = Bag::create([
            'bag_number' => $bagNumber,
            'status' => 'sealed',
        ]);

        foreach ($parcels as $parcel) {
            BagItem::create([
                'bag_id' => $bag->id,
                'parcel_id' => $parcel->id,
            ]);
            $parcel->update([
                'status' => 'Bagged',
                'is_scanned' => true,
            ]);
        }

        return back()->with('success', 'Bag created successfully!');
    }
}
