<?php

namespace App\Http\Controllers\Admin;

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

class StoreController extends Controller
{
    public function index()
    {
        $storeRecord = \Cache::get('storeRecord');
        if (!$storeRecord) {
            $storeRecord = Store::selectRaw('COUNT(id) AS totalStore')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeStore')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeStorePercent')
                ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inactiveStore')
                ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inactiveStorePercent')
                ->selectRaw('(SELECT COUNT(id) FROM stores WHERE DATE(created_at) = CURDATE()) AS todayStore')
                ->selectRaw('(SELECT COUNT(id) FROM stores WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())) AS thisMonthStore')
                ->selectRaw('((SELECT COUNT(id) FROM stores WHERE DATE(created_at) = CURDATE()) / NULLIF(COUNT(id), 0)) * 100 AS todayStorePercent')
                ->selectRaw('((SELECT COUNT(id) FROM stores WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())) / NULLIF(COUNT(id), 0)) * 100 AS thisMonthStorePercent')
                ->get()
                ->toArray();

            \Cache::put('storeRecord', $storeRecord);
        }

        $data['storeRecord'] = $storeRecord;
        return view('admin.store.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;

        $items = Store::query()
            ->with(['user:id,firstname,lastname,username,email,image,image_driver'])
            ->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($items)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('store', function ($item) {
                return $item->name;
            })

            ->addColumn('owner', 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('menu', function ($item) {
                return '<span class="badge bg-soft-secondary text-secondary">'.$item->productsCount().'</span>';
            })

            ->addColumn('shipping_charge', function ($item) {
                $chargeBadgeClass = $item->shipping_charge == 1 ? 'success' : 'danger';
                $charge = $item->shipping_charge == 1 ? 'Active' : 'Inactive';
                return '<span class="badge bg-soft-'.$chargeBadgeClass.' text-'.$chargeBadgeClass.'"><span class="legend-indicator bg-'.$chargeBadgeClass.'"></span>'.$charge.'</span>';
            })
            ->addColumn('delivery_note', function ($item) {
                $noteBadgeClass = $item->delivery_note == 'Enable' ? 'success' : 'danger';
                return '<span class="badge bg-soft-'.$noteBadgeClass.' text-'.$noteBadgeClass.'"><span class="legend-indicator bg-'.$noteBadgeClass.'"></span>'.$item->delivery_note.'</span>';
            })

            ->addColumn('status', function ($item) {
                $statusClass = $item->status == 1 ? 'success' : 'danger';
                $status = $item->status == 1 ? 'Active' : 'Inactive';
                return '<span class="badge bg-soft-'.$statusClass.' text-'.$statusClass.'"><span class="legend-indicator bg-'.$statusClass.'"></span>'.$status.'</span>';
            })
            ->addColumn('action', function ($item) {
                $detailsUrl = route('admin.store.details', $item->id);
                $menuUrl = route('admin.menu.index', $item->id);
                $orderUrl = route('admin.order.index', $item->id);
                return '<div class="btn-group" role="group">
                        <a href="' . $detailsUrl . '" class="btn btn-white btn-sm">
                        <i class="bi-eye fill me-1"></i> ' . trans("Details") . '
                      </a>
                    <div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                      <a href="' . $menuUrl . '" class="dropdown-item text-secondary">
                        <i class="fal fa-utensils me-1"></i> ' . trans("Menu") . '
                      </a>
                      <a href="'.$orderUrl.'" class="dropdown-item text-secondary">
                        <i class="fal fa-tags me-1"></i> ' . trans("Orders") . '
                      </a>
                      </div>
                    </div>
                  </div>';
            })

            ->rawColumns(['store','owner', 'menu', 'shipping_charge', 'delivery_note','status','action'])
            ->make(true);
    }

    public function details($id)
    {
        $data['store'] = Store::findOrFail($id);
        return view('admin.store.store_details', $data);
    }
}
