<?php

namespace App\Http\Controllers\Admin;

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

class ShippingController extends Controller
{
    public function index()
    {
        $storeProductRecord = \Cache::get('storeProductRecord');
        if (!$storeProductRecord) {
            $storeProductRecord = StoreShipping::selectRaw('COUNT(id) AS totalStoreShipping')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeStoreShipping')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeStoreShippingPercent')
                ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inactiveStoreShipping')
                ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inactiveStoreShippingPercent')
                ->selectRaw('(SELECT COUNT(id) FROM store_shippings WHERE DATE(created_at) = CURDATE()) AS todayStoreShipping')
                ->selectRaw('(SELECT COUNT(id) FROM store_shippings WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())) AS thisMonthStoreShipping')
                ->selectRaw('((SELECT COUNT(id) FROM store_shippings WHERE DATE(created_at) = CURDATE()) / NULLIF(COUNT(id), 0)) * 100 AS todayStoreShippingPercent')
                ->selectRaw('((SELECT COUNT(id) FROM store_shippings WHERE MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE())) / NULLIF(COUNT(id), 0)) * 100 AS thisMonthStoreShippingPercent')
                ->get()
                ->toArray();
            \Cache::put('storeProductRecord', $storeProductRecord);
        }

        $data['storeProductRecord'] = $storeProductRecord;
        return view('admin.shipping.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 = StoreShipping::query()
            ->with(['user:id,firstname,lastname,username,email,image,image_driver','store:id,name'])
            ->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('address', '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%");
                    })
                    ->orWhereHas('store', function ($q3) use ($search) {
                        $q3->where('name', 'LIKE', "%$search%");
                    });
            })
            ->when(!empty($filterInput), function ($query) use ($filterInput) {
                return $query->where('address', '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%");
                    })
                    ->orWhereHas('store', function ($q3) use ($filterInput) {
                        $q3->where('name', '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('store', function ($item) {
                $storeUrl = route('admin.store.details', $item->store_id);
                return '<a href="'.$storeUrl.'" class="text-secondary">' . optional($item->store)->name . '</a>';
            })
            ->addColumn('cost', function ($item) {
                return currencyPosition(getAmount($item->charge));
            })

            ->addColumn('address', function ($item) {
                return $item->address;
            })
            ->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('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(['store','cost','owner', 'address', 'status', 'created_at'])
            ->make(true);
    }
}
