<?php

namespace App\Http\Controllers\Branch;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Branch;
use App\Models\Bag;
use App\Models\Parcel;
use Illuminate\Support\Facades\Auth;

class BaggingController extends Controller
{
    public function index()
    {
        return view('branch.bagging');
    }

    public function addParcel(Request $request)
    {
        $request->validate([
            'parcel_tracking_id' => 'required|exists:parcels,tracking_id',
        ]);

        $parcel = Parcel::where('tracking_id', $request->parcel_tracking_id)->firstOrFail();
        $destinationBranchId = $parcel->branch_id; // Assuming the parcel has a branch_id for its destination

        // Find or create a bag for this destination
        $bag = Bag::firstOrCreate(
            [
                'origin_branch_id' => Auth::user()->branch_id,
                'destination_branch_id' => $destinationBranchId,
                'status' => 'open',
            ],
            [
                'bag_number' => 'BAG-' . uniqid(),
            ]
        );

        // Attach the parcel to the bag if it's not already there
        if (!$bag->parcels->contains($parcel->id)) {
            $bag->parcels()->attach($parcel->id);
        }

        // Load the bag with its parcels for the response
        $bag->load('parcels', 'destinationBranch');

        return response()->json(['success' => 'Parcel added to bag.', 'bag' => $bag]);
    }

    public function seal(Bag $bag)
    {
        $bag->update(['status' => 'sealed']);

        return response()->json(['success' => 'Bag sealed successfully.']);
    }
}
