<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\HasilPrediksi;
use App\Models\DataPenjualan;
use App\Models\Helpdesk;
use Illuminate\Http\Request;
use Carbon\Carbon;

class DataUserControllers extends Controller
{
    public function index()
    {
        $users = User::where('role', 'user')
            ->withCount(['hasilPrediksis', 'helpdesks'])
            ->latest()
            ->get();
        
        return view('admin.data-user.index', compact('users'));
    }

    public function show($id)
    {

        Carbon::setLocale('id');

        $user = User::withCount(['hasilPrediksis', 'helpdesks'])->findOrFail($id);
        

        $prediksis = HasilPrediksi::where('user_id', $id)
            ->latest()
            ->get()
            ->map(function($item) {
                return [
                    'jenis' => 'Melakukan Prediksi Stok',
                    'tanggal' => Carbon::parse($item->created_at)->locale('id'),
                    'status' => 'Berhasil',
                    'badge' => 'success',
                    'icon' => 'fas fa-robot text-primary'
                ];
            });

        $uploads = DataPenjualan::where('user_id', $id)
            ->latest()
            ->get()
            ->map(function($item) {
                return [
                    'jenis' => 'Update Data Penjualan',
                    'tanggal' => Carbon::parse($item->created_at)->locale('id'),
                    'status' => 'Terbaru',
                    'badge' => 'info',
                    'icon' => 'fas fa-file-upload text-info'
                ];
            });

        $bantuans = Helpdesk::where('user_id', $id)
            ->latest()
            ->get()
            ->map(function($item) {
                return [
                    'jenis' => 'Mengirim Tiket Bantuan',
                    'tanggal' => Carbon::parse($item->created_at)->locale('id'),
                    'status' => $item->reply ? 'Selesai' : 'Menunggu',
                    'badge' => $item->reply ? 'success' : 'warning',
                    'icon' => 'fas fa-headset text-warning'
                ];
            });

        $riwayatAktivitas = collect()
            ->concat($prediksis)
            ->concat($uploads)
            ->concat($bantuans)

            ->sortByDesc(function ($aktivitas) {
                return $aktivitas['tanggal']->timestamp;
            })
            ->unique(function ($aktivitas) {
                return $aktivitas['jenis'] . $aktivitas['tanggal']->format('Y-m-d H:i');
            })
            ->take(10);

        return view('admin.data-user.detail', compact('user', 'riwayatAktivitas'));
    }

    public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->delete();
        
        return redirect()->route('admin.data-user')->with('success', 'User berhasil dihapus.');
    }
}