<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Delivery;
use App\Models\Order;
use App\Models\Product;
use App\Models\Transaction;
use Exception;
use App\Models\User;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    //view
    public function index(){
        //count number of customer
        $count_customer = User::where("user_group", "2")->count();
        //count product
        $count_product = Product::count();
        //count sales
        $count_sales = Order::where("sale_status", "success")->count();
        //count delivery
        $count_delivery = Delivery::where("status", "delivered")->count();
        //count menu
        $count_menu = Category::count();
        //get sales
        $sales = Order::orderBy("created_at", "DESC")->limit(5)->get();
        //get customers
        $customers = User::where("user_group", "2")->limit(5)->get();
        //get products
        $products = Product::orderBy("created_at", "DESC")->limit(5)->get();
        //get delivery
        $menus = Category::orderBy("created_at", "DESC")->limit(5)->get();

        return view("admin.index")->with([
            "count_customer" => $count_customer,
            "count_product" => $count_product,
            "count_sales" => $count_sales,
            "count_delivery" => $count_delivery,
            "count_menu" => $count_menu,

            "sales" => $sales,
            "customers" => $customers,
            "products" => $products,
            "menus" => $menus,
        ]);
    }

    public function profile(){
        return view("admin.people.profile");
    }

    public function customers(){
        //fetch all the customer
        $customers = User::where("user_group", "2")->orderBy("created_at", "DESC")->get();
        return view("admin.people.customers")->with("customers", $customers);
    }

    public function deleteModal($id){
        $customer = User::find($id);
        $view = view('modals.people.delete', compact('customer'))->render();
        return response()->json(['html'=>$view]);
    }

    public function delete(Request $request){
        try {
            User::where("id", $request->id)->delete();
            return redirect()->back()->with("success", "Customer Deleted");
        } catch (Exception $e) {
            return redirect()->back()->with("error", "Oops, there was an error!!");
        }
    }

    public function payments(){
        $payments = Transaction::orderBy("created_at", "DESC")->get();
        return view("admin.payments")->with(["payments" => $payments]);
    }
}
