<?php

namespace App\Http\Controllers\admin;

use App\Exports\OrdersExport;
use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\PendingOrder;
use App\Models\Product;
use App\Models\Systemlog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Mail\OrderTrackingUpdated;
use Illuminate\Support\Facades\Mail;
use Maatwebsite\Excel\Facades\Excel;

class ordersController extends Controller
{
    public function order_index()
    {
        return view('admin.order.order');
    }

    public function orders_get(Request $request)
    {

      $data = Order::query();
        if ($request->has('payment_method') && $request->payment_method != '') {
            $paymentMethod = $request->payment_method;
            $data->where('payment_method', 'LIKE', '%' . $paymentMethod . '%');
        }

        if ($request->startDate && $request->endDate) {
            $data->whereBetween('created_at', [$request->startDate . ' 00:00:00', $request->endDate . ' 23:59:59']);
        }
        // ->join('product', 'deals.product_id', '=', 'product.id') // joining the contacts table , where user_id and contact_user_id are sam
        return datatables()->of($data)
            ->addIndexColumn()

            ->addColumn('action', function ($data) {
                if ($data->processing == 0 && $data->cancellation == 0) {
                    $btn = '<div class="dropdown">
                    <button type="button" class="btn p-0 dropdown-toggle hide-arrow" data-bs-toggle="dropdown">
                        <i class="bx bx-dots-vertical-rounded"></i>
                    </button>
                    <div class="dropdown-menu">

                        <a class="dropdown-item reject" href="javascript:void(0);" data-id="' . $data->id . '">
                        <i class="bx bx-edit"></i>
                        </i>Request Rejected
                        </a>
                        <a class="dropdown-item cancel" href="javascript:void(0);" data-id="' . $data->id . '">
                        <i class="bx bx-trash me-1"></i> Cancel Order
                    </a>
                    </div>
                </div>';
                    return $btn;
                } else {
                    $btn = '<div class="dropdown">
                <button type="button" class="btn p-0 dropdown-toggle hide-arrow" data-bs-toggle="dropdown">
                    <i class="bx bx-dots-vertical-rounded"></i>
                </button>
                <div class="dropdown-menu">

                    <a class="dropdown-item edit" href="javascript:void(0);" data-id="' . $data->id . '">
                    <i class="bx bx-edit"></i>
                    </i>More
                    </a>
                    <a class="dropdown-item cancel" href="javascript:void(0);" data-id="' . $data->id . '">
                    <i class="bx bx-trash me-1"></i> Cancel Order
                </a>
                </div>
            </div>';
                    return $btn;
                }
            })

            ->addColumn('product_name', function ($data) {
                $productData = Product::where('id', $data->product_id)->first();
                $productName = $productData->product_name ?? 'Product Not available';

                // Initialize an empty label string
                $label = '';

                // Check if the product was created today
                if (Carbon::parse($data->created_at)->isToday()) {
                    $label .= ' <span class="label label-success" style="color:#FFFFFF;background-color:#28a745;padding:3px;border-radius:4px;">New</span>';
                }

                // Check if the product has a cancellation request
                if ($data->processing == 0 && $data->cancellation == 0) {
                    $label .= ' <span class="label label-warning" style="color:#ffc107">Cancellation Requested</span>';
                }
                Log::info('Product Name: ' . $productName);
                Log::info('Label: ' . $label);
                // Return the product name with the appropriate labels
                return $productName . $label;
            })

            ->addColumn('sku', function ($data) {
                $productData = Product::where('id', $data->product_id)->first();
                $productsku = $productData->sku ?? 'Sku not found';
                return $productsku;
            })
             ->addColumn('totalprice', function ($data) {
                $totprice=$data->total;
                $shippingcost=$data->service_fee;
                 $tot=$totprice + $shippingcost;
                 $totalprice='LKR ' . number_format($tot, 2);
                return $totalprice;
            })
              ->addColumn('koko_order_id', function ($data) {
                $kokid=$data->koko_order_id;

                return $kokid;
            })
             ->addColumn('mintpay_order_id', function ($data) {
                $mintpayid=$data->mintpay_order_id;

                return $mintpayid;
            })

            ->addColumn('created_at', function ($data) {
                $createdat=$data->created_at;
                $formattedDate = Carbon::parse($createdat)->format('Y M d h:i A');
                return $formattedDate;
            })
            ->addColumn('status', function ($data) {
                if ($data->processing == 1 && $data->ready==0 && $data->picked == 0 && $data->on_the_way == 0 && $data->delivered == 0) {
                    $status = '<span class="text-secondary">Processing</span>';
                }
                elseif ($data->processing == 1 &&  $data->ready==1 &&  $data->picked == 0 && $data->on_the_way == 0 && $data->delivered == 0) {
                    $status = '<span class="text-success">Ready for Pickup</span>';
                }
                 elseif ($data->processing == 1 &&  $data->ready==1 && $data->picked == 1 && $data->on_the_way == 0 && $data->delivered == 0) {
                    $status = '<span class="text-success">Picked</span>';
                } elseif ($data->processing == 1 &&  $data->ready==1 && $data->picked == 1 && $data->on_the_way == 1 && $data->delivered == 0) {
                    $status = '<span class="text-info">On the way</span>';
                } elseif ($data->processing == 1 &&  $data->ready==1 && $data->picked == 1 && $data->on_the_way == 1 && $data->delivered == 1) {
                    $status = '<span class="text-success">Delivered</span>';
                } elseif ($data->processing == 0 &&  $data->ready==0 && $data->picked == 0 && $data->on_the_way == 0 && $data->delivered == 0 && $data->cancellation == 1) {
                    $status = '<span class="text-danger">Cancelled</span>';
                } else {
                    $status = '<span class="text-danger">Cancellation Progress</span>';
                }

                return $status;
            })

            ->rawColumns(['product_name', 'action', 'status', 'sku','totalprice','created_at','koko_order_id'])
            ->make(true);
    }

    public function cancel_order(Request $request)
    {
        $user=Auth::user();
        $orderData = Order::find($request->id);
       // $orderData->delete();
         $orderData->processing=0;
         $orderData->cancellation = 1;
         $result = $orderData->update();
        if ($result) {
            $message = "Order id ".$orderData->order_id ." cancelled  by ".$user->name." at ".now()->toDateTimeString();
            Systemlog::create([
                'message' => $message,
            ]);
            $this->soldqty_reverse($orderData->product_id,$orderData->quantity);
            $this->updateproductstock($orderData->product_id,$orderData->quantity);
            return response()->json(['code' => 'true', 'msg' => 'Order cancelled']);
        } else {
            return response()->json(['code' => 'false', 'msg' => 'somethong went wrong']);
        }
    }

    public function soldqty_reverse($productid,$qty){
      $productData=Product::find($productid);
      $productData->order=$productData->order - $qty;
      $productData->update();
    }

    public function updateproductstock($product_id,$qty){
        $product=Product::find($product_id);
        $product->qty=$product->qty + $qty;
        $product->update();

    }
    public function request_cancel(Request $request)
    {
        $user=Auth::user();
        $orderData = Order::find($request->id);
        $orderData->cancellation = null;
        $orderData->processing = 1;
        $result = $orderData->update();
        if ($result) {
            $message = "Order id ".$orderData->order_id ." customer request cancelled  by ".$user->name." at ".now()->toDateTimeString();
            Systemlog::create([
                'message' => $message,
            ]);
            return response()->json(['code' => 'true', 'msg' => 'Request cancelled']);
        } else {
            return response()->json(['code' => 'false', 'msg' => 'somethong went wrong']);
        }
    }

    public function editorder(Request $request)
    {

        $dataid=$request->id;
        $ordereddata=Order::where('id',$dataid)->first();

        if($ordereddata->userid == "Guest"){
            $orderData = DB::table('order')
            ->join('product', 'order.product_id', '=', 'product.id')
            ->join('shipping_zone', 'order.zone_id', '=', 'shipping_zone.id')
            ->select(
                'order.*',
                'order.created_at as order_created_at',
                'product.*',
                'shipping_zone.*',

            )
            ->where('order.id', $dataid)
            ->first();
        }
        else{
             $orderData = DB::table('order')
            ->join('product', 'order.product_id', '=', 'product.id')
            ->join('users', 'order.userid', '=', 'users.id')
            ->join('shipping_zone', 'order.zone_id', '=', 'shipping_zone.id')
            ->select(
                'order.*',
                 'product.*',
                  'order.created_at as order_created_at',
                  'users.*',
                'shipping_zone.*',

            )
            ->where('order.id', $dataid)
            ->first();

        }


        return $orderData;
    }

    public function order_update(Request $request)
    {

        $id = $request->id;
        $tracking = $request->tracking;
        $processing_value = $request->processing;
        $ready_value = $request->ready;
        $shipped_value = $request->shipped;
        $onthe_way_value = $request->onthe_way;
        $completed_value = $request->order_complete;
        $data = Order::where('order_id', $id)->pluck('id')->first();
        $record = Order::find($data)->update([
            'tracking' => $tracking ?? null,
            'processing' => $processing_value ?? 1,
            'ready' => $ready_value ?? 0,
            'picked' => $shipped_value ?? 0,
            'on_the_way' => $onthe_way_value ?? 0,
            'delivered' => $completed_value ?? 0,
        ]);

        $orderData=Order::where('order_id', $id)->first();
        if($orderData->userid !=null){
            $orderId=$orderData->order_id;
            $updatedTrackingNumber = $tracking ?? null;

            // Send the email
            Mail::to($orderData->email)->send(new OrderTrackingUpdated($updatedTrackingNumber,$orderId));
        }
        if ($record) {
            return response()->json(['code' => 'true', 'msg' => 'Order updated']);
        } else {
            return response()->json(['code' => 'false', 'msg' => 'somethong went wrong']);
        }
    }

    public function order_history(){
        return view('admin.order.order_history');
    }
    public function get_order_data(Request $request){
        $startDate = $request->input('startDate');
        $endDate = $request->input('endDate');
        $orders = $this->getOrdersBetweenDates($startDate, $endDate);
        return response()->json($orders);
    }

    private function getOrdersBetweenDates($startDate, $endDate){
        $orders = Order::whereBetween('created_at', [$startDate, $endDate])->get();
        return $orders;
    }

    public function order_report_dashboard(){
        return view('admin.order.report.order_report_dashboard');
    }
     public function downloadReport(Request $request)
    {

        $validated = $request->validate([
            'report_type' => 'required|in:koko,cod,card,mintpay,all',
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'format' => 'required|in:excel,csv,pdf'
        ]);



        $fileName = $this->generateFileName(
            $validated['report_type'],
            $validated['start_date'],
            $validated['end_date'],
            $validated['format']
        );


        return Excel::download(
            new OrdersExport(
                $validated['report_type'],
                $validated['start_date'],
                $validated['end_date']
            ),
            $fileName
        );
    }

    private function generateFileName($type, $startDate, $endDate, $format)
    {
        $typeMap = [
            'koko' => 'KoKo_Orders',
             'mintpay' => 'Mintpay_Orders',
            'cod' => 'COD_Orders',
            'card' => 'Card_Orders',
            'all' => 'All_Orders'
        ];

        $extension = [
            'excel' => 'xlsx',
            'csv' => 'csv',
            'pdf' => 'pdf'
        ];

        return sprintf(
            '%s_%s_to_%s.%s',
            $typeMap[$type],
            $startDate,
            $endDate,
            $extension[$format]
        );
    }

    public function pending_orders_index()
    {
        return view('admin.order.pending');
    }

    public function pending_orders_get(Request $request)
    {
        $data = PendingOrder::query();

        if ($request->has('payment_method') && $request->payment_method != '') {
            $paymentMethod = $request->payment_method;
            $data->where('payment_method', 'LIKE', '%' . $paymentMethod . '%');
        }

        if ($request->has('status') && $request->status != '') {
            $data->where('status', $request->status);
        }

        if ($request->startDate && $request->endDate) {
            $data->whereBetween('created_at', [$request->startDate . ' 00:00:00', $request->endDate . ' 23:59:59']);
        }

        return datatables()->of($data)
            ->addIndexColumn()
            ->addColumn('action', function ($data) {
                return '<button class="btn btn-primary btn-sm view-pending-details" data-id="' . $data->id . '">View Details</button>';
            })
            ->addColumn('customer_name', function ($data) {
                $payload = $data->payload;
                if (!$payload) {
                    return 'N/A';
                }
                $firstName = $payload['cus_first_name'] ?? $payload['first_name'] ?? '';
                $lastName = $payload['cus_last_name'] ?? $payload['last_name'] ?? '';
                return trim($firstName . ' ' . $lastName) ?: 'N/A';
            })
            ->addColumn('customer_email', function ($data) {
                $payload = $data->payload;
                return $payload['cus_email'] ?? $payload['email'] ?? 'N/A';
            })
            ->addColumn('total_amount', function ($data) {
                $payload = $data->payload;
                if (!$payload) {
                    return 'N/A';
                }
                $amount = $payload['amount'] ?? $payload['total'] ?? 0;
                return 'LKR ' . number_format((float)$amount, 2);
            })
            ->addColumn('created_at', function ($data) {
                return Carbon::parse($data->created_at)->format('Y M d h:i A');
            })
            ->addColumn('status', function ($data) {
                if ($data->status == 'completed') {
                    return '<span class="badge bg-success">Completed</span>';
                } elseif ($data->status == 'failed') {
                    return '<span class="badge bg-danger">Failed</span>';
                } else {
                    return '<span class="badge bg-warning text-dark">Pending</span>';
                }
            })
            ->rawColumns(['action', 'status'])
            ->make(true);
    }

    public function pending_order_details(Request $request)
    {
        $pendingOrder = PendingOrder::find($request->id);
        if (!$pendingOrder) {
            return response()->json(['error' => 'Pending order not found'], 404);
        }

        $payload = $pendingOrder->payload;
        $products = [];
        if ($payload && !empty($payload['productid'])) {
            $productIds = explode(',', $payload['productid']);
            $quantities = explode(',', $payload['order_qty'] ?? '');
            $colors = explode(',', $payload['order_color'] ?? '');

            foreach ($productIds as $index => $pid) {
                $product = Product::find($pid);
                $products[] = [
                    'name' => $product->product_name ?? 'Unknown Product',
                    'sku' => $product->sku ?? 'N/A',
                    'quantity' => $quantities[$index] ?? 1,
                    'color' => $colors[$index] ?? 'N/A'
                ];
            }
        }

        return response()->json([
            'pending_order' => $pendingOrder,
            'products' => $products
        ]);
    }
}
