<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class OrderTrackingController extends Controller
{
    /**
     * Show the order tracking form.
     */
    public function index()
    {
        return view('order.tracking');
    }

    /**
     * Track order by order number or phone number.
     */
    public function track(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'search_type' => 'required|in:order_number,phone',
            'search_value' => 'required|string|max:255'
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $searchType = $request->search_type;
        $searchValue = $request->search_value;

        $ordersQuery = Order::with(['orderItems.product', 'user']);

        // If user is authenticated, only show their orders
        if (auth()->check()) {
            $ordersQuery->where('user_id', auth()->id());
        }

        if ($searchType === 'order_number') {
            $orders = $ordersQuery->where('order_number', 'like', '%' . $searchValue . '%')
                          ->orderBy('created_at', 'desc')
                          ->get();
        } else {
            $orders = $ordersQuery->where('customer_phone', 'like', '%' . $searchValue . '%')
                          ->orderBy('created_at', 'desc')
                          ->get();
        }

        if ($orders->isEmpty()) {
            $errorMessage = auth()->check() 
                ? 'No orders found for the provided information in your account.'
                : 'No orders found. Please log in to view your order details.';
            
            return back()->with('error', $errorMessage)
                        ->withInput();
        }

        return view('order.tracking-results', compact('orders', 'searchType', 'searchValue'));
    }

    /**
     * Show detailed order information.
     */
    public function show($orderNumber)
    {
        $order = Order::with(['orderItems.product', 'user'])
                     ->where('order_number', $orderNumber)
                     ->where('user_id', auth()->id()) // Only show user's own orders
                     ->first();

        if (!$order) {
            abort(404, 'Order not found or you do not have permission to view this order');
        }

        return view('order.tracking-details', compact('order'));
    }

    /**
     * Get order status timeline.
     */
    public function getStatusTimeline($orderNumber)
    {
        // Check if user is authenticated and owns the order
        if (!auth()->check()) {
            return response()->json(['error' => 'Authentication required'], 401);
        }

        $order = Order::where('order_number', $orderNumber)
                     ->where('user_id', auth()->id())
                     ->first();

        if (!$order) {
            return response()->json(['error' => 'Order not found'], 404);
        }

        $timeline = [];

        // Order placed
        $timeline[] = [
            'status' => 'placed',
            'title' => 'অর্ডার করা হয়েছে',
            'description' => 'আপনার অর্ডার সফলভাবে করা হয়েছে',
            'date' => $order->created_at,
            'completed' => true
        ];

        // Order confirmed
        if ($order->confirmed_at) {
            $timeline[] = [
                'status' => 'confirmed',
                'title' => 'অর্ডার নিশ্চিত করা হয়েছে',
                'description' => 'আপনার অর্ডার নিশ্চিত করা হয়েছে এবং প্রস্তুত করা হচ্ছে',
                'date' => $order->confirmed_at,
                'completed' => true
            ];
        } else {
            $timeline[] = [
                'status' => 'confirmed',
                'title' => 'অর্ডার নিশ্চিত করা হয়েছে',
                'description' => 'অর্ডার নিশ্চিতকরণের অপেক্ষায়',
                'date' => null,
                'completed' => false
            ];
        }

        // Order shipped
        if ($order->shipped_at) {
            $timeline[] = [
                'status' => 'shipped',
                'title' => 'অর্ডার শিপ করা হয়েছে',
                'description' => 'আপনার অর্ডার শিপ করা হয়েছে এবং পথে রয়েছে',
                'date' => $order->shipped_at,
                'completed' => true
            ];
        } else {
            $timeline[] = [
                'status' => 'shipped',
                'title' => 'অর্ডার শিপ করা হয়েছে',
                'description' => 'শিপমেন্টের জন্য প্রস্তুত করা হচ্ছে',
                'date' => null,
                'completed' => false
            ];
        }

        // Order delivered
        if ($order->delivered_at) {
            $timeline[] = [
                'status' => 'delivered',
                'title' => 'অর্ডার ডেলিভার করা হয়েছে',
                'description' => 'আপনার অর্ডার সফলভাবে ডেলিভার করা হয়েছে',
                'date' => $order->delivered_at,
                'completed' => true
            ];
        } else {
            $timeline[] = [
                'status' => 'delivered',
                'title' => 'অর্ডার ডেলিভার করা হয়েছে',
                'description' => 'অর্ডার শীঘ্রই ডেলিভার করা হবে',
                'date' => null,
                'completed' => false
            ];
        }

        return response()->json(['timeline' => $timeline]);
    }
}