<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Order;
use Yajra\DataTables\DataTables;
use App\Models\OrderStatusHistory;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf;
class OrderController extends Controller
{


    public function getOrders(Request $request)
    {
        if ($request->ajax()) {

            $orders = Order::with(['user', 'items.product.images'])
                ->orderBy('id', 'DESC');

            return DataTables::of($orders)

                ->addColumn('order_number', fn($row) => '#' . $row->order_number)

                ->addColumn(
                    'created_at',
                    fn($row) =>
                    $row->created_at->format('M d, Y')
                )

                ->addColumn('customer', function ($row) {
                    return $row->user
                        ? '<a href="#" class="link-primary fw-medium">' . $row->user->name . '</a>'
                        : '-';
                })

                ->addColumn('product', function ($row) {
                    $item = $row->items->first();
                    if (!$item) return '-';

                    $image = $item->product?->images->first()?->image ?? null;
                    $imgTag = $image
                        ? '<img src="' . asset('uploads/products/' . $image) . '" width="40" class="me-2 rounded">'
                        : '';

                    return $imgTag . $item->product->name;
                })

                ->addColumn('total', fn($row) => '₹' . number_format($row->total_amount, 2))

                ->addColumn('payment_status', function ($row) {
                    return match ($row->payment_status) {
                        'paid' => '<span class="badge bg-success">Paid</span>',
                        'failed' => '<span class="badge bg-danger">Failed</span>',
                        default => '<span class="badge bg-light text-dark">Pending</span>',
                    };
                })

                ->addColumn('items', function ($row) {

                    if ($row->items->isEmpty()) {
                        return '-';
                    }

                    $html = '<ul class="mb-0 ps-3">';

                    foreach ($row->items as $item) {
                        $html .= '<li class="text-nowrap">'
                            . e($item->product->name)
                            . ' <span class="text-muted">(x' . $item->quantity . ')</span>'
                            . '</li>';
                    }

                    $html .= '</ul>';

                    return $html;
                })


                //        ->addColumn('items', function ($row) {

                //     $names = $row->items->map(fn($i) => $i->product->name)->implode(', ');

                //     return '
                //         <span class="badge bg-info" title="'.$names.'">
                //             '.$row->items->count().' Items
                //         </span>
                //     ';
                // })


                ->addColumn('delivery_number', fn() => '-')

                ->addColumn('order_status', function ($row) {
                    return match ($row->order_status) {
                        'processing' => '<span class="badge bg-info rounded-pill">Processing</span>',
                        'shipped'    => '<span class="badge bg-primary rounded-pill">Shipped</span>',
                        'in_transit'    => '<span class="badge bg-purple rounded-pill">In Transit</span>',
                        'delivered'  => '<span class="badge bg-success rounded-pill">Delivered</span>',
                        'cancelled'  => '<span class="badge bg-danger rounded-pill">Cancelled</span>',
                        'refund'     => '<span class="badge bg-warning rounded-pill">Refund</span>',
                        default      => '<span class="badge bg-secondary rounded-pill">Pending</span>',
                    };
                })

                ->addColumn('action', function ($row) {
                    return '
    <div class="d-flex gap-2">
        <a href="' . route('get-order', ['orderid' => $row->id]) . '" class="btn btn-light btn-sm">
            <iconify-icon icon="solar:eye-broken"></iconify-icon>
        </a>
      <a href="javascript:void(0)"
   class="btn btn-soft-primary btn-sm editStatusBtn"
   data-id="' .  $row->id . '"
   data-status="' .  $row->order_status  . '">
    <iconify-icon icon="solar:pen-2-broken"></iconify-icon>
</a>


        <button class="btn btn-soft-danger btn-sm deleteOrder" data-id="' . $row->id . '">
            <iconify-icon icon="solar:trash-bin-minimalistic-2-broken"></iconify-icon>
        </button>
    </div>';
                })

                ->rawColumns([
                    'customer',
                    'product',
                    'payment_status',
                    'items',
                    'order_status',
                    'action'
                ])
                ->make(true);
        }
    }




    public function updateStatus(Request $request)
    {
        $request->validate([
            'order_status' => 'required|string|in:processing,shipped,in_transit,delivered,cancelled,refund',
            'description'  => 'required|string'
        ]);

        DB::transaction(function () use ($request) {

            // 1️⃣ Update current order status
            $order = Order::findOrFail($request->id);
            $order->order_status = $request->order_status;
            $order->save();

            // 2️⃣ Insert into status history table
            OrderStatusHistory::create([
                'order_id'    => $order->id,
                'status'      => $request->order_status,
                'description' => $request->description ?? $this->defaultDescription($request->order_status),
                'status_date' => now(),
            ]);
        });

        return response()->json([
            'success' => true,
            'message' => 'Order status updated successfully'
        ]);
    }

    public function getOrder(Request $request)
    {

        $order = Order::with([
            'items.product.images',
            'statusHistory',
            'user'
        ])->findOrFail($request->orderid);
        //print_r($order);die();
        return view('admin.order-details', compact('order'));
    }

    public function downloadInvoice(Request $request)
    {

        $order = Order::with([
            'items.product.images',
            'statusHistory',
            'user'
        ])->findOrFail($request->orderid);
        //print_r($order);die();
        return view('admin.invoice', compact('order'));
    }

    public function deleteOrder($id)
{
    try {
        $order = Order::findOrFail($id);

        // delete related items first
        $order->items()->delete();
        $order->statusHistory()->delete();

        // delete invoice file if exists
        if ($order->invoice_path && file_exists(public_path($order->invoice_path))) {
            unlink(public_path($order->invoice_path));
        }

        $order->delete();

        return response()->json([
            'status' => true,
            'message' => 'Order deleted successfully'
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'status' => false,
            'message' => 'Failed to delete order'
        ], 500);
    }
}

}
