<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\StoreCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Yajra\DataTables\Facades\DataTables;

class CategoryController extends Controller
{
    public function index()
    {
        $storeCategoryRecord = \Cache::get('storeCategoryRecord');
        if (!$storeCategoryRecord) {
            $storeCategoryRecord = StoreCategory::selectRaw('COUNT(id) AS totalStoreCategory')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeStoreCategory')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeStoreCategoryPercent')
                ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inactiveStoreCategory')
                ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inactiveStoreCategoryPercent')
                ->selectRaw('(SELECT COUNT(id) FROM store_categories WHERE DATE(created_at) = CURDATE()) AS todayStoreCategory')
                ->selectRaw('(SELECT COUNT(id) FROM store_categories WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())) AS thisMonthStoreCategory')
                ->selectRaw('((SELECT COUNT(id) FROM store_categories WHERE DATE(created_at) = CURDATE()) / NULLIF(COUNT(id), 0)) * 100 AS todayStoreCategoryPercent')
                ->selectRaw('((SELECT COUNT(id) FROM store_categories WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())) / NULLIF(COUNT(id), 0)) * 100 AS thisMonthStoreCategoryPercent')
                ->get()
                ->toArray();
            \Cache::put('storeCategoryRecord', $storeCategoryRecord);
        }

        $data['storeCategoryRecord'] = $storeCategoryRecord;
        return view('admin.category.index',$data);
    }

    public function search(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterInput = $request->filterInput;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $purchasePlan = StoreCategory::query()
            ->with(['user:id,firstname,lastname,username,email,image,image_driver'])
            ->withcount(['activeProducts'])
            ->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('name', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q2) use ($search) {
                            $q2->where('firstname', 'LIKE', "%$search%")
                                ->orWhere('lastname', 'LIKE', "%$search%")
                                ->orWhere('username', 'LIKE', "%$search%")
                                ->orWhere('email', 'LIKE', "%$search%");
                        });
            })
            ->when(!empty($filterInput), function ($query) use ($filterInput) {
                return $query->where('name', 'LIKE', "%$filterInput%")
                    ->orWhereHas('user', function ($q2) use ($filterInput) {
                    $q2->where('firstname', 'LIKE', "%$filterInput%")
                        ->orWhere('lastname', 'LIKE', "%$filterInput%")
                        ->orWhere('username', 'LIKE', "%$filterInput%")
                        ->orWhere('email', 'LIKE', "%$filterInput%");
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });

        return DataTables::of($purchasePlan)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                return $item->name;
            })
            ->addColumn('active_menu', function ($item) {
                return '<span class="badge bg-soft-secondary text-secondary">'.$item->active_products_count.'</span>';
            })
            ->addColumn('creator', function ($item) {
                $url = route('admin.user.view.profile', $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="'.$url.'">
                            <div class="flex-shrink-0">
                              ' . $item->user->profilePicture() . '
                            </div>
                            <div class="flex-grow-1 ms-3">
                              <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                              <span class="fs-6 text-body">' . optional($item->user)->email . '</span>
                            </div>
                      </a>';
            })
            ->addColumn('status', function ($item) {
                $badgeClass = $item->status == 1 ? 'success text-success' : 'danger text-danger';
                $legendBgClass = $item->status == 1 ? 'success' : 'danger';
                $status = $item->status == 1 ? 'Active' : 'Inactive';
                return '<span class="badge bg-soft-'.$badgeClass.'"><span class="legend-indicator bg-'.$legendBgClass.'"></span>'.$status.'</span>';
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at);
            })
            ->rawColumns(['name','creator', 'active_menu', 'status', 'created_at'])
            ->make(true);
    }
}
