<?php

namespace App\Http\Controllers\Admin\Branch;

use App\Http\Controllers\Controller;
use App\Models\Parcel;
use App\Models\Rider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class BranchController extends Controller
{
    public function dashboard()
    {
        $assignedShipments = Parcel::where('status', 'Out for Delivery')->whereDate('created_at', today())->count();
        $deliveredParcels = Parcel::where('status', 'Delivered')->count();
        $failedDeliveries = Parcel::where('status', 'Failed Delivery')->count();
        $returnShipments = Parcel::where('status', 'Returned to Origin')->count();
        // Use correct columns based on schema
        // $codCollected = DB::table('cod_collections')
        //     ->whereDate('collection_date', today())
        //     ->sum('collected_amount');
        $codCollected = 0;
        $codDeposited = DB::table('bank_deposits')
            ->whereDate('deposit_date', today())
            ->sum('amount');
        $moveToOrigin = Parcel::where('status', 'Forwarded to Hub')->count();
        $received = Parcel::where('status', 'Received at Hub')->count();
        $bagsReceived = DB::table('bags')->whereDate('created_at', today())->count();
        $unbagging = DB::table('bags')->where('status', 'unbagged')->count();
        $pickupOrders = Parcel::where('status', 'Pending Pickup')->count();
        $pendingOrders = Parcel::where('status', 'Pending')->count();
        $reattemptPending = Parcel::where('status', 'Reattempt')->count();
        $amountPendingToDeposit = $codCollected - $codDeposited;
        $complaints = DB::table('complaints')->where('status', 'Open')->count();
        $internalUpdates = DB::table('internal_updates')->whereDate('created_at', today())->count();
        $recentParcels = Parcel::with('rider', 'seller')->latest()->limit(10)->get();

        return view('branch.dashboard', compact(
            'assignedShipments',
            'deliveredParcels',
            'failedDeliveries',
            'returnShipments',
            'codCollected',
            'codDeposited',
            'moveToOrigin',
            'received',
            'bagsReceived',
            'unbagging',
            'pickupOrders',
            'pendingOrders',
            'reattemptPending',
            'amountPendingToDeposit',
            'complaints',
            'internalUpdates',
            'recentParcels'
        ));
    }

    public function bagging()
    {
        return view('admin.branch.bagging');
    }

    /**
     * Branch Dispatch screen: list parcels, search, bulk select.
     */
    public function dispatch(Request $request)
    {
        $q = trim((string) $request->get('q'));

        $parcels = Parcel::query()
            ->when($q !== '', function ($query) use ($q) {
                $query->where(function ($sub) use ($q) {
                    $sub->where('tracking_id', 'like', "%$q%")
                        ->orWhere('recipient_name', 'like', "%$q%")
                        ->orWhere('city', 'like', "%$q%")
                        ->orWhere('order_reference_number', 'like', "%$q%");
                });
            })
            ->whereIn('status', ['Picked Up', 'In Transit', 'Pending', 'Out for Delivery'])
            ->latest()
            ->limit(200)
            ->get();

        $riders = Rider::orderBy('name')->get();

        return view('admin.branch.dispatch', compact('parcels', 'riders', 'q'));
    }

    /**
     * Assign selected parcels to a rider and mark as Out for Delivery.
     */
    public function assign(Request $request)
    {
        $data = $request->validate([
            'rider_id' => 'required|exists:riders,id',
            'parcel_ids' => 'required|array',
            'parcel_ids.*' => 'integer|exists:parcels,id',
        ]);

        DB::transaction(function () use ($data) {
            Parcel::whereIn('id', $data['parcel_ids'])
                ->update([
                    'assigned_rider_id' => $data['rider_id'],
                    'status' => 'Out for Delivery',
                ]);
        });

        return back()->with('success', 'Parcels assigned to rider successfully.');
    }

    /**
     * Scan a parcel by tracking ID to mark as scanned (optional flow helper).
     */
    public function scan(Request $request)
    {
        $data = $request->validate([
            'tracking_id' => 'required|string',
        ]);

        $parcel = Parcel::where('tracking_id', $data['tracking_id'])->first();
        if (!$parcel) {
            return back()->withErrors(['tracking_id' => 'Tracking ID not found']);
        }

        $parcel->update(['is_scanned' => true]);

        return back()->with('success', "Scanned: {$parcel->tracking_id}");
    }

    /**
     * Simple printable manifest view for selected parcels.
     */
    public function manifest(Request $request)
    {
        $ids = $request->get('parcel_ids', []);
        $parcels = Parcel::with('rider', 'seller')->whereIn('id', $ids)->get();
        return view('admin.branch.manifest', compact('parcels'));
    }

    public function deliveriesAssigned()
    {
        $parcels = Parcel::whereNotNull('assigned_rider_id')->where('status', 'Out for Delivery')->get();
        return view('admin.branch.deliveries-assigned', compact('parcels'));
    }
}
