<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Validator;

class OrderController extends Controller
{
    public function index(Request $request)
    {
        $query = Order::where('user_id', auth()->id());

        $this->applyFilters($request, $query);

        $orders = $query->latest()->paginate(10);

        // Counts for tabs
        $counts = Order::where('user_id', auth()->id())
            ->selectRaw("COUNT(CASE WHEN status != 'Pending' THEN 1 END) as booked, COUNT(CASE WHEN status = 'Pending' THEN 1 END) as unbooked")
            ->first();
        $allCount = $counts->booked + $counts->unbooked;
        $bookedCount = $counts->booked;
        $unbookedCount = $counts->unbooked;
        $logsCount = Order::where('user_id', auth()->id())->onlyTrashed()->count();

        return view('seller.orders.index', compact('orders', 'allCount', 'bookedCount', 'unbookedCount', 'logsCount'));
    }

    public function create()
    {
        return view('seller.orders.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'recipient_name' => 'required|string|max:255',
            'recipient_phone' => 'required|string|max:255',
            'recipient_address' => 'required|string',
            'recipient_city' => 'required|string|max:255',
            'cod_amount' => 'required|numeric|min:0',
            'parcel_weight' => 'required|numeric|min:0',
        ]);

        $order = new Order($request->all());
        $order->user_id = auth()->id();
        $order->tracking_id = 'PCL' . uniqid();
        $order->save();

        return redirect()->route('seller.orders.index')->with('success', 'Order created successfully.');
    }

    public function show(Order $order)
    {
        return view('seller.orders.show', compact('order'));
    }

    public function edit(Order $order)
    {
        return view('seller.orders.edit', compact('order'));
    }

    public function update(Request $request, Order $order)
    {
        $request->validate([
            'recipient_name' => 'required|string|max:255',
            'recipient_phone' => 'required|string|max:255',
            'recipient_address' => 'required|string',
            'recipient_city' => 'required|string|max:255',
            'cod_amount' => 'required|numeric|min:0',
            'parcel_weight' => 'required|numeric|min:0',
        ]);

        $order->update($request->all());

        return redirect()->route('seller.orders.index')->with('success', 'Order updated successfully.');
    }

    public function destroy(Order $order)
    {
        $order->delete();

        return redirect()->route('seller.orders.index')->with('success', 'Order cancelled successfully.');
    }

    public function transit(Request $request)
    {
        $query = Order::where('user_id', auth()->id())->whereIn('status', ['Picked Up', 'In Transit', 'Out for Delivery']);

        $this->applyFilters($request, $query);

        $orders = $query->latest()->paginate(10);

        // Counts for tabs
        $counts = Order::where('user_id', auth()->id())
            ->whereIn('status', ['Picked Up', 'In Transit', 'Out for Delivery'])
            ->selectRaw("COUNT(*) as all_count, COUNT(CASE WHEN status = 'Picked Up' THEN 1 END) as picked_by, COUNT(CASE WHEN status = 'In Transit' THEN 1 END) as warehouse, COUNT(CASE WHEN status = 'Out for Delivery' THEN 1 END) as out_for_delivery")
            ->first();
        $allCount = $counts->all_count;
        $pickedByCount = $counts->picked_by;
        $warehouseCount = $counts->warehouse;
        $outForDeliveryCount = $counts->out_for_delivery;

        return view('seller.orders.transit', compact('orders', 'allCount', 'pickedByCount', 'warehouseCount', 'outForDeliveryCount'));
    }

    public function verification(Request $request)
    {
        $query = Order::where('user_id', auth()->id())->where('status', 'Under Verification');

        $this->applyFilters($request, $query);

        $orders = $query->latest()->paginate(10);

        return view('seller.orders.verification', compact('orders'));
    }

    public function logs(Request $request)
    {
        $query = Order::where('user_id', auth()->id())->withTrashed();

        $this->applyFilters($request, $query);

        $orders = $query->latest()->paginate(10);

        // Counts for tabs
        $counts = Order::where('user_id', auth()->id())
            ->withTrashed()
            ->selectRaw("COUNT(*) as all_count, COUNT(CASE WHEN status = 'Booked' THEN 1 END) as booked, COUNT(CASE WHEN status = 'Pending' THEN 1 END) as unbooked, COUNT(CASE WHEN status = 'In Transit' THEN 1 END) as in_transit, COUNT(CASE WHEN status = 'Delivered' THEN 1 END) as delivered, COUNT(CASE WHEN status = 'Returned' THEN 1 END) as returned, COUNT(CASE WHEN deleted_at IS NOT NULL THEN 1 END) as cancelled")
            ->first();
        $allCount = $counts->all_count;
        $bookedCount = $counts->booked;
        $unbookedCount = $counts->unbooked;
        $inTransitCount = $counts->in_transit;
        $deliveredCount = $counts->delivered;
        $returnedCount = $counts->returned;
        $cancelledCount = $counts->cancelled;

        return view('seller.orders.logs', compact('orders', 'allCount', 'bookedCount', 'unbookedCount', 'inTransitCount', 'deliveredCount', 'returnedCount', 'cancelledCount'));
    }

    public function airwayBills(Request $request)
    {
        $query = Order::where('user_id', auth()->id());

        // Status/Tab filtering
        $status = $request->get('tab');
        if ($status) {
            $query->where('status', $status);
        }

        // Search filtering
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('tracking_id', 'like', "%$search%")
                  ->orWhere('recipient_name', 'like', "%$search%");
            });
        }

        // Date filtering
        if ($request->filled('from_date')) {
            $query->whereDate('created_at', '>=', $request->get('from_date'));
        }
        if ($request->filled('to_date')) {
            $query->whereDate('created_at', '<=', $request->get('to_date'));
        }

        $orders = $query->latest()->paginate(10);

        // Counts for tabs
        $allCount = Order::where('user_id', auth()->id())->count();
        $bookedCount = Order::where('user_id', auth()->id())->where('status', 'Booked')->count();
        $unbookedCount = Order::where('user_id', auth()->id())->where('status', 'Pending')->count();
        $inTransitCount = Order::where('user_id', auth()->id())->where('status', 'In Transit')->count();

        return view('seller.orders.airway-bills', compact('orders', 'allCount', 'bookedCount', 'unbookedCount', 'inTransitCount'));
    }

    public function bulkUpload(Request $request)
    {
        if ($request->isMethod('post')) {
            $request->validate(['csv_file' => 'required|file|mimes:csv,txt']);

            $records = array_map('str_getcsv', file($path));

            if (count($records) > 0) {
                $orders = [];
                foreach ($records as $record) {
                    $validator = Validator::make([
                        'recipient_name' => $record[0] ?? null,
                        'recipient_phone' => $record[1] ?? null,
                        'recipient_address' => $record[2] ?? null,
                        'recipient_city' => $record[3] ?? null,
                        'cod_amount' => $record[4] ?? null,
                        'parcel_weight' => $record[5] ?? null,
                    ], [
                        'recipient_name' => 'required|string|max:255',
                        'recipient_phone' => 'required|string|max:255',
                        'recipient_address' => 'required|string',
                        'recipient_city' => 'required|string|max:255',
                        'cod_amount' => 'required|numeric|min:0',
                        'parcel_weight' => 'required|numeric|min:0',
                    ]);

                    if ($validator->passes()) {
                        $orders[] = [
                            'recipient_name' => $record[0],
                            'recipient_phone' => $record[1],
                            'recipient_address' => $record[2],
                            'recipient_city' => $record[3],
                            'cod_amount' => $record[4],
                            'parcel_weight' => $record[5],
                            'status' => 'Pending',
                            'user_id' => auth()->id(),
                            'tracking_id' => 'PCL' . uniqid(),
                            'created_at' => now(),
                            'updated_at' => now(),
                        ];
                    } else {
                        // Optionally, you could log these errors or return them to the user
                    }
                }
                Order::insert($orders);
                return redirect()->route('seller.orders.logs')->with('success', 'Orders uploaded successfully.');
            }
        }
        return view('seller.orders.bulk-upload');
    }

    public function printAirwayBills(Request $request)
    {
        $orderIds = $request->input('orders', []);
        $orders = Order::whereIn('id', $orderIds)->get();

        if ($orders->isEmpty()) {
            return redirect()->back()->with('error', 'No orders selected for printing.');
        }

        $pdf = PDF::loadView('seller.orders.airway_bill_pdf', compact('orders'));
        return $pdf->download('airway-bills.pdf');
    }

    private function applyFilters(Request $request, $query)
    {
        // Status/Tab filtering
        $status = $request->get('tab');
        if ($status) {
            if ($status === 'Cancelled') {
                $query->onlyTrashed();
            } else {
                $query->where('status', $status);
            }
        }

        // Search filtering
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('tracking_id', 'like', "%$search%")
                  ->orWhere('recipient_name', 'like', "%$search%");
            });
        }

        // Date filtering
        if ($request->filled('from_date')) {
            $query->whereDate('created_at', '>=', $request->get('from_date'));
        }
        if ($request->filled('to_date')) {
            $query->whereDate('created_at', '<=', $request->get('to_date'));
        }
    }
}
