<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Addiction;
use App\Models\History;
use App\Models\Item;
use App\Models\Likert;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware('role:user');
    }

    public function index()
    {
        $addictions = Addiction::where('status', 'active')
            ->orderBy('min_percentage', 'desc')
            ->get();
        return view('user.dashboard', compact('addictions'));
    }

    public function history()
    {
        $histories = History::with('user', 'addiction')
            ->where('user_id', Auth::id())
            ->orderBy('created_at', 'desc')
            ->get();

        return view('user.history', compact('histories'));
    }

    public function addiction()
    {
        $items = Item::where('status', 'active')->get();

        $likerts = Likert::orderBy('score')->get();
        return view('user.addiction', compact('items', 'likerts'));
    }

    public function storeAddiction(Request $request)
    {
        $values     = $request->values;
        $answers    = $request->answers;
        $maxLikert  = Likert::orderBy('score', 'desc')->first()->score;

        $userScores = [];
        $maxScores  = [];

        foreach ($values as $key => $value) {
            $userScores[]   = $value * $answers[$key];
            $maxScores[]    = $value * $maxLikert;
        }

        $totalUserScore = array_sum($userScores);
        $totalMaxScore  = array_sum($maxScores);

        $percentage = round(($totalUserScore / $totalMaxScore) * 100, 2);

        $addiction = Addiction::where('min_percentage', '<=', $percentage)
                    ->where('max_percentage', '>=', $percentage)
                    ->where('status', 'active')
                    ->first();

        if ($addiction === null) {
            return redirect()->back()->with('error', 'Terjadi kesalahan saat mencari jenis kecanduan');
        }

        History::create([
            'user_id'       => Auth::id(),
            'addiction_id'  => $addiction->id,
            'result'        => $percentage.'%',
        ]);

        return redirect()->route('user.history')->with('success', 'Berhasil menambahkan riwayat');
    }
}
