<?php

namespace App\Http\Controllers\Backend\Order;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Color;
use App\Models\Company;
use App\Models\Genre;
use App\Models\Goods;
use App\Models\Order;
use App\Models\OrderAttachment;
use App\Models\OrderDetails;
use App\Models\Product;
use App\Models\ProductUnit;
use App\Models\Status;
use App\Models\ProformaInvoice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index() {
        $title = "Orders List";
        $buyer = Auth::guard('buyer')->user();
        if ($buyer) {
            $orders = Order::orderBy('id', 'DESC')->where('buyer_id', $buyer->id)->get();
        } else {
            $orders = Order::orderBy('id', 'DESC')->get();
        }
        return view('backend.pages.order.index', get_defined_vars());
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        $title = 'Product List';
        $buyer = Auth::guard('buyer')->user();
        $categories = Genre::where('status', 'Active')->get();
        // dd($categories);
        $products = Goods::where('status', 'Active')->paginate(30);
        // $colors = Color::where('status', 'Display')->get();
        $colors = Color::where('status', 'Display')->get();
        $units = ProductUnit::where('status', 'Active')->get();
        $orderLastData = Order::latest('id')->first();
        if ($orderLastData) {
            $orderData = $orderLastData->id + 1;
        } else {
            $orderData = 1;
        }
        $orderCode = 'ORD' . str_pad($orderData, 5, "0", STR_PAD_LEFT);
        return view('backend.pages.order.create', get_defined_vars());
    }

    public function admincreate() {
        $title = 'Product List';
        $buyer = Auth::guard('web')->user();
        $categories = Genre::where('status', 'Active')->get();
        // dd($categories);
        $products = Goods::where('status', 'Active')->paginate(30);
        // $colors = Color::where('status', 'Display')->get();
        $colors = Color::where('status', 'Display')->get();
        $units = ProductUnit::where('status', 'Active')->get();
        $orderLastData = Order::latest('id')->first();
        if ($orderLastData) {
            $orderData = $orderLastData->id + 1;
        } else {
            $orderData = 1;
        }
        $orderCode = 'ORD' . str_pad($orderData, 5, "0", STR_PAD_LEFT);
        return view('backend.pages.order.admin_order_create', get_defined_vars());
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        $validate = Validator::make($request->all(), [
            'order_code' => 'required',
            'style_no' => 'required',
            'po_number' => 'required',
            'goods_name' => 'required',
            'thumbnail' => 'required',
            'quantity' => 'required',
            'rate' => 'required',
            'price' => 'required',
        ]);
        if ($validate->fails()) {
            return back()->with('error', 'Validation Error!!');
        }
        $buyer = Auth::guard('buyer')->user();

        $order = new Order();
        $order->buyer_id = $buyer->id;
        $order->order_code = $request->order_code;
        $order->style_no = $request->style_no;
        $order->po_number = $request->po_number;
        $order->amount = $request->amount;
        $order->note = $request->note;
        $order->status = 'Pending';
        $order->progress_id = Status::first();
        $order->save();

        $attachments = $request->file('attachments');
        if ($attachments != null) {
            foreach ($attachments as $key => $attachment) {
                $orderAttachment = 'attachment_' . time() . '_' . $key . '.' . $attachment->getClientOriginalExtension();
                $attachment->move(public_path('/uploads/orders/'), $orderAttachment);
                $orderFile = new OrderAttachment();
                $orderFile->order_id = $order->id;
                $orderFile->buyer_id = $buyer->id;
                $orderFile->type = 'PO';
                $orderFile->attachment = $orderAttachment;
                $orderFile->save();
            }
        }

        if ($request->goods_name) {
            foreach ($request->goods_name as $key => $item) {
                $color = Color::find($request->color[$key]);
                $unit = ProductUnit::find($request->unit[$key]);
                $orderDetails = new OrderDetails();
                $orderDetails->order_id = $order->id;
                $orderDetails->goods_name = $item;
                $orderDetails->category = $request->category[$key];
                $orderDetails->size = $request->size[$key];
                $orderDetails->color = $color ? $color->name : null;
                $orderDetails->unit = $unit ? $unit->name : null;
                // $orderDetails->thumbnail = $request->thumbnail[$key];
                if ($request->hasFile('thumbnail') && $request->file('thumbnail')[$key]->isValid()) {
                    $thumbnail = $request->file('thumbnail')[$key];
                    $thumbnailName = 'thumbnail_' . time() . '.' . $thumbnail->getClientOriginalExtension();
                    $thumbnail->move(public_path('uploads/orders'), $thumbnailName);
                    // $orderDetails->thumbnail = public_path('uploads/orders/') . $thumbnailName;
                    $orderDetails->thumbnail = $thumbnailName;
                } else {
                    $orderDetails->thumbnail = $request->thumbnail[$key];
                }
                $orderDetails->quantity = $request->quantity[$key];
                $orderDetails->rate = $request->rate[$key];
                $orderDetails->price = $request->price[$key];
                $orderDetails->save();
            }
        }

        //   setNotification("New Order", "uploads/orders/".$orderAttachment);

        return redirect()->route('buyer.order.index')->with('success', 'Order placed successfully!!');
    }
    public function aadminstore(Request $request) {
        // dd($request->all());
        $validate = Validator::make($request->all(), [
            'order_code' => 'required',
            'style_no' => 'required',
            'po_number' => 'required',
            'goods_name' => 'required',
            'thumbnail' => 'required',
            'quantity' => 'required',
            'rate' => 'required',
            'price' => 'required',
        ]);
        if ($validate->fails()) {
            return back()->with('error', 'Validation Error!!');
        }
        $buyer = Auth::guard('web')->user();

        $order = new Order();
        $order->buyer_id = $request->buyer_id;
        // dd( $order);
        $order->order_code = $request->order_code;
        $order->style_no = $request->style_no;
        $order->po_number = $request->po_number;
        $order->amount = $request->amount;
        $order->note = $request->note;
        $order->status = 'Pending';
        $order->progress_id = Status::first();
        $order->save();

        $attachments = $request->file('attachments');
        if ($attachments != null) {
            foreach ($attachments as $key => $attachment) {
                $orderAttachment = 'attachment_' . time() . '_' . $key . '.' . $attachment->getClientOriginalExtension();
                $attachment->move(public_path('/uploads/orders/'), $orderAttachment);
                $orderFile = new OrderAttachment();
                $orderFile->order_id = $order->id;
                $orderFile->buyer_id = $buyer->id;
                $orderFile->type = 'PO';
                $orderFile->attachment = $orderAttachment;
                $orderFile->save();
            }
        }

        if ($request->goods_name) {
            foreach ($request->goods_name as $key => $item) {
                $color = Color::find($request->color[$key]);
                $unit = ProductUnit::find($request->unit[$key]);
                $orderDetails = new OrderDetails();
                $orderDetails->order_id = $order->id;
                $orderDetails->goods_name = $item;
                $orderDetails->category = $request->category[$key];
                $orderDetails->size = $request->size[$key];
                $orderDetails->color = $color ? $color->name : null;
                $orderDetails->unit = $unit ? $unit->name : null;
                // $orderDetails->thumbnail = $request->thumbnail[$key];
                if ($request->hasFile('thumbnail') && $request->file('thumbnail')[$key]->isValid()) {
                    $thumbnail = $request->file('thumbnail')[$key];
                    $thumbnailName = 'thumbnail_' . time() . '.' . $thumbnail->getClientOriginalExtension();
                    $thumbnail->move(public_path('uploads/orders'), $thumbnailName);
                    // $orderDetails->thumbnail = public_path('uploads/orders/') . $thumbnailName;
                    $orderDetails->thumbnail = $thumbnailName;
                } else {
                    $orderDetails->thumbnail = $request->thumbnail[$key];
                }
                $orderDetails->quantity = $request->quantity[$key];
                $orderDetails->rate = $request->rate[$key];
                $orderDetails->price = $request->price[$key];
                $orderDetails->save();
            }
        }

        //   setNotification("New Order");

        return redirect()->route('order.index')->with('success', 'Order placed successfully!!');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Order  $order
     * @return \Illuminate\Http\Response
     */
    public function show($id) {
        $title = "Order Invoice";
        $companyInfo = Company::where('status', 'Active')->first();
        $order = Order::find($id);
        $quantity = $order->details->sum('quantity');
        return view('backend.pages.order.invoice', get_defined_vars());
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Order  $order
     * @return \Illuminate\Http\Response
     */
    public function edit($id) {
        $title = "Edit Order";
        $companyInfo = Company::where('status', 'Active')->first();
        $order = Order::find($id);
        $status = Status::all();
        $quantity = $order->details->sum('quantity');
        return view('backend.pages.order.edit', get_defined_vars());
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Order  $order
     * @return \Illuminate\Http\Response
     */

    // public function update(Request $request, $id) {
    //     // $validate = Validator::make($request->all(), [
    //     //     'hs_code' => 'required|array',
    //     //     'hs_code.*' => 'required',
    //     // ]);

    //     // if ($validate->fails()) {
    //     //     return back()->with('error', 'Validation Error!!')->withErrors($validate)->withInput();
    //     // }
    //     // dd($request->all());

    //     $order = Order::find($id);
    //     $order->progress_id = $request->progress_id;
    //     $order->save();

    //     if (!$order) {
    //         return back()->with('error', 'Order not found!');
    //     }

    //     // Assuming an order can have multiple details, use get() instead of first()
    //     $details = OrderDetails::where('order_id', $id)->get();

    //     if ($request->has('rate')) {
    //         foreach ($request->rate as $key => $rate) {
    //             if (isset($details[$key])) {
    //                 $details[$key]->rate = $rate;
    //                 $details[$key]->price = $request->price[$key];
    //                 $details[$key]->save();
    //             }
    //         }
    //     }

    //     return redirect()->route('order.index')->with('success', 'Order updated successfully!!');
    // }

    public function update(Request $request, $id) {
        // dd($request->all());
        $order = Order::find($id);
        if (!$order) {
            return back()->with('error', 'Order not found!');
        }

        $order->progress_id = $request->progress_id;
        $order->save();

        $details = OrderDetails::where('order_id', $order->id)->get();

        // $totalPrice = 0;
        // if ($request->has('rate')) {
        //     foreach ($request->rate as $key => $rate) {
        //         if (isset($details[$key])) {
        //             $details[$key]->rate = $rate;
        //             $details[$key]->price = $request->price[$key];
        //             $details[$key]->save();

        //             $totalPrice += $details[$key]->price;
        //         }
        //     }
        // }

        $totalPrice = 0;
        if ($request->has('rate') && $details->isNotEmpty()) {
            foreach ($request->rate as $key => $rate) {
                $detail = $details->get($key);
                if ($detail !== null) {
                    $detail->rate = $rate;
                    $detail->price = $request->price[$key] + $detail->price;
                    $detail->save();
                    $totalPrice += $detail->price;
                }
            }
        }

        $order->amount += $totalPrice;
        $order->save();

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Order  $order
     * @return \Illuminate\Http\Response
     */
    public function destroy($id) {
        $order = Order::find($id);
        $order->details()->delete();
        $order->delete();

        return back()->with('success', 'Order deleted successfully!!');
    }

    public function status($id, $status) {
        $user = Auth::user();
        $order = Order::find($id);
        $order->status = $status;
        if ($status == 'Approved') {
            $order->approved_by = $user->id;
        } else {
            $order->rejected_by = $user->id;
        }
        $order->save();

        return back()->with('success', 'Order has been approved.');
    }

    public function upload(Request $request) {
        $request->validate([
            'product_thumbnail' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);
        if ($request->hasFile('product_thumbnail')) {
            $thumbnail = $request->file('product_thumbnail');
            $thumbnailName = 'thumbnail_' . time() . '.' . $thumbnail->getClientOriginalExtension();
            $thumbnail->move(public_path('uploads/goods'), $thumbnailName);
            return response()->json(['thumbnail_url' => '/uploads/goods/' . $thumbnailName], 200);
        }
        return response()->json(['error' => 'No thumbnail provided'], 400);
    }
}
