<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth;

class UserOrderController extends Controller
{
    public function orderSummary()
    {
        // Authenticate user via JWT
        $user = JWTAuth::parseToken()->authenticate();

        if (!$user) {
            return response()->json([
                'status' => false,
                'message' => 'Unauthorized'
            ], 401);
        }

        // -------------------------------------
        // Get all orders
        // -------------------------------------
        $orders = $user->orders()->with('invoice')->get();

        // -------------------------------------
        // Counts
        // -------------------------------------
        $totalOrders = $orders->count();
        $delivered   = $orders->where('status', 'delivered')->count();
        $inTransit   = $orders->where('status', '!=', 'delivered')->count();
        $active      = $totalOrders;

        // -------------------------------------
        // Total Amount = Invoice.total_with_gst
        // -------------------------------------
        $totalAmount = $orders->sum(function ($o) {
            return $o->invoice->final_amount_with_gst ?? 0;
        });

        // Format total amount in K, L, Cr
        $formattedAmount = $this->formatIndianNumber($totalAmount);

        return response()->json([
            'status' => true,

            'summary' => [
                'active_orders'     => $active,
                'in_transit_orders' => $inTransit,
                'delivered_orders'  => $delivered,
                'total_value'       => $formattedAmount,  // formatted value
                'total_raw'         => $totalAmount       // original value
            ]
        ]);
    }

    /**
     * Convert number into Indian Format:
     * 1000 -> 1K
     * 100000 -> 1L
     * 10000000 -> 1Cr
     */
    private function formatIndianNumber($num)
    {
        if ($num >= 10000000) {
            return round($num / 10000000, 1) . 'Cr';
        }

        if ($num >= 100000) {
            return round($num / 100000, 1) . 'L';
        }

        if ($num >= 1000) {
            return round($num / 1000, 1) . 'K';
        }

        return (string)$num;
    }

    public function allOrders()
{
    $user = JWTAuth::parseToken()->authenticate();

    if (!$user) {
        return response()->json([
            'success' => false,
            'message' => 'Unauthorized'
        ], 401);
    }

    // Fetch orders for this user
    $orders = $user->orders()
        ->with(['invoice', 'shipments'])
        ->orderBy('id', 'desc')
        ->get()
        ->map(function ($o) {
            return [
                'order_id'   => $o->order_id,
                'status'     => $o->status,
                'amount'     => $o->ttl_amount,
                'description'=> "Order from {$o->origin} to {$o->destination}",
                'created_at' => $o->created_at,
            ];
        });

    return response()->json([
        'success' => true,
        'orders'  => $orders
    ]);
}

public function orderDetails($order_id)
{
    $user = JWTAuth::parseToken()->authenticate();

    $order = $user->orders()
        ->with(['items'])
        ->where('order_id', $order_id)
        ->first();

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

    return response()->json([
        'success' => true,
        'order'   => $order
    ]);
}


public function orderShipment($order_id)
{
    $user = JWTAuth::parseToken()->authenticate();

    // Get order
    $order = $user->orders()->where('order_id', $order_id)->first();

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

    // Find shipment only for this order
    $shipment = $order->shipments()
        ->with(['items' => function ($q) use ($order) {
            $q->where('order_id', $order->id);
        }])
        ->first();

    return response()->json([
        'success' => true,
        'shipment' => $shipment
    ]);
}


public function orderInvoice($order_id)
{
    $user = JWTAuth::parseToken()->authenticate();

    $order = $user->orders()
        ->with('invoice.items')
        ->where('order_id', $order_id)
        ->first();

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

    return response()->json([
        'success' => true,
        'invoice' => $order->invoice
    ]);
}

public function trackOrder($order_id)
{
    $user = JWTAuth::parseToken()->authenticate();

    $order = $user->orders()
        ->with('shipments')
        ->where('order_id', $order_id)
        ->first();

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

    $shipment = $order->shipments()->first();

    return response()->json([
        'success' => true,
        'track' => [
            'order_id' => $order->order_id,
            'shipment_status' => $shipment->status ?? 'pending',
            'shipment_date'   => $shipment->shipment_date ?? null,
        ]
    ]);
}

public function allInvoices()
{
    $user = JWTAuth::parseToken()->authenticate();

    if (!$user) {
        return response()->json([
            'success' => false,
            'message' => 'Unauthorized'
        ], 401);
    }

    // Fetch all invoices of customer
    $invoices = $user->invoices()
        ->withCount('installments')
        ->orderBy('id', 'desc')
        ->get()
        ->map(function ($invoice) {
            return [
                'invoice_id'        => $invoice->id,
                'invoice_number'    => $invoice->invoice_number,
                'invoice_date'      => $invoice->invoice_date,
                'status'            => $invoice->status,
                'amount'            => $invoice->final_amount_with_gst,
                'formatted_amount'  => $this->formatIndianNumber($invoice->final_amount_with_gst),
                'pdf_url'           => $invoice->pdf_path ? url($invoice->pdf_path) : null,
                'installment_count' => $invoice->installments_count,
            ];
        });

    return response()->json([
        'success'  => true,
        'invoices' => $invoices
    ]);
}

public function invoiceInstallmentsById($invoice_id)
{
    $user = \PHPOpenSourceSaver\JWTAuth\Facades\JWTAuth::parseToken()->authenticate();

    if (! $user) {
        return response()->json(['success' => false, 'message' => 'Unauthorized'], 401);
    }

    // Find invoice by numeric id and ensure it belongs to logged-in user (invoice.customer_id = user.id)
    $invoice = \App\Models\Invoice::where('id', (int)$invoice_id)
        ->where('customer_id', $user->id)
        ->with(['installments' => function($q){
            $q->orderBy('installment_date', 'ASC')->orderBy('id', 'ASC');
        }])
        ->first();

    if (! $invoice) {
        return response()->json([
            'success' => false,
            'message' => 'Invoice not found for this customer'
        ], 404);
    }

    return response()->json([
        'success'        => true,
        'invoice_id'     => $invoice->id,
        'invoice_number' => $invoice->invoice_number,
        'installments'   => $invoice->installments
    ]);
}

public function invoiceDetails($invoice_id)
{
    $user = JWTAuth::parseToken()->authenticate();

    if (! $user) {
        return response()->json(['success' => false, 'message' => 'Unauthorized'], 401);
    }

    $invoice = \App\Models\Invoice::where('id', $invoice_id)
        ->where('customer_id', $user->id)
        ->with('items')
        ->first();

    if (! $invoice) {
        return response()->json(['success' => false, 'message' => 'Invoice not found'], 404);
    }

    return response()->json([
        'success' => true,
        'invoice' => $invoice
    ]);
}





}
