<?php

namespace App\Http\Controllers;

use App\Models\Satisfaction;
use App\Http\Requests\StoreSatisfactionRequest;
use App\Http\Requests\UpdateSatisfactionRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Barryvdh\DomPDF\Facade\PDF;

class SatisfactionController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        if (Auth::user()->role === 'admin') {
            $satisfactions = Satisfaction::latest()->get();
        } else {
            $satisfactions = Satisfaction::where('user_id', Auth::id())->latest()->get();
        }
        return view('satisfactions.index', compact('satisfactions'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        // Kode lama yang membatasi satu kali pengisian per user telah dihapus
        return view('satisfactions.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'q1' => 'required|integer|min:1|max:5',
            'q2' => 'required|integer|min:1|max:5',
            'q3' => 'required|integer|min:1|max:5',
            'q4' => 'required|integer|min:1|max:5',
            'q5' => 'required|integer|min:1|max:5',
            'q6' => 'required|integer|min:1|max:5',
            'q7' => 'required|integer|min:1|max:5',
            'q8' => 'required|integer|min:1|max:5',
            'q9' => 'required|integer|min:1|max:5',
            'q10' => 'required|integer|min:1|max:5',
            'q11' => 'required|integer|min:1|max:5',
            'q12' => 'required|integer|min:1|max:5',
            'q13' => 'required|integer|min:1|max:5',
            'q14' => 'required|integer|min:1|max:5',
            'q15' => 'required|integer|min:1|max:5',
            'kritik_saran' => 'nullable|string',
        ]);

        $data = $request->all();
        $data['user_id'] = Auth::id();

        Satisfaction::create($data);

        return redirect()->route('satisfactions.index')
            ->with('success', 'Terima kasih! Penilaian kepuasan pelanggan Anda telah berhasil disimpan.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Satisfaction $satisfaction)
    {
        // Pastikan pengguna hanya bisa melihat data survei miliknya sendiri
        if (Auth::user()->role === 'pelanggan') {
            if ($satisfaction->user_id !== Auth::id()) {
                abort(403, 'Unauthorized action.');
            }
        }

        return view('satisfactions.show', compact('satisfaction'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Satisfaction $satisfaction)
    {
        // Pastikan pengguna hanya bisa mengedit data survei miliknya sendiri
        if ($satisfaction->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        return view('satisfactions.edit', compact('satisfaction'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Satisfaction $satisfaction)
    {
        // Pastikan pengguna hanya bisa mengupdate data survei miliknya sendiri
        if ($satisfaction->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        $request->validate([
            'q1' => 'required|integer|min:1|max:5',
            'q2' => 'required|integer|min:1|max:5',
            'q3' => 'required|integer|min:1|max:5',
            'q4' => 'required|integer|min:1|max:5',
            'q5' => 'required|integer|min:1|max:5',
            'q6' => 'required|integer|min:1|max:5',
            'q7' => 'required|integer|min:1|max:5',
            'q8' => 'required|integer|min:1|max:5',
            'q9' => 'required|integer|min:1|max:5',
            'q10' => 'required|integer|min:1|max:5',
            'q11' => 'required|integer|min:1|max:5',
            'q12' => 'required|integer|min:1|max:5',
            'q13' => 'required|integer|min:1|max:5',
            'q14' => 'required|integer|min:1|max:5',
            'q15' => 'required|integer|min:1|max:5',
            'kritik_saran' => 'nullable|string',
        ]);

        $satisfaction->update($request->all());

        return redirect()->route('satisfactions.index')
            ->with('success', 'Penilaian kepuasan pelanggan berhasil diperbarui.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Satisfaction $satisfaction)
    {
        // Pastikan pengguna hanya bisa menghapus data survei miliknya sendiri
        if ($satisfaction->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        $satisfaction->delete();

        return redirect()->route('satisfactions.index')
            ->with('success', 'Penilaian kepuasan pelanggan berhasil dihapus.');
    }

    /**
     * Generate PDF for a single satisfaction
     */
    public function pdf(Satisfaction $satisfaction)
    {
        // Pastikan pengguna hanya bisa melihat data survei miliknya sendiri atau admin
        if (Auth::user()->role === 'pelanggan') {
            if ($satisfaction->user_id !== Auth::id()) {
                abort(403, 'Unauthorized action.');
            }
        }

        $pdf = PDF::loadView('satisfactions.pdf', compact('satisfaction'));
        return $pdf->download('penilaian-kepuasan-' . $satisfaction->id . '.pdf');
    }

    /**
     * Generate PDF for all satisfactions (admin only)
     */
    public function allPdf(Request $request)
    {
        // Hanya admin yang bisa akses
        if (Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized action.');
        }

        // Ambil semua data atau filter jika diperlukan
        $satisfactions = Satisfaction::latest()->get();

        // Jika ada filter, tambahkan ke array filters
        $filters = [];
        if ($request->filled('tanggal_mulai')) {
            $satisfactions = $satisfactions->filter(function ($item) use ($request) {
                return $item->created_at->format('Y-m-d') >= $request->tanggal_mulai;
            });
            $filters['tanggal_mulai'] = $request->tanggal_mulai;
        }

        if ($request->filled('tanggal_selesai')) {
            $satisfactions = $satisfactions->filter(function ($item) use ($request) {
                return $item->created_at->format('Y-m-d') <= $request->tanggal_selesai;
            });
            $filters['tanggal_selesai'] = $request->tanggal_selesai;
        }

        if ($request->filled('rating_min')) {
            $satisfactions = $satisfactions->filter(function ($item) use ($request) {
                return $item->average_score >= $request->rating_min;
            });
            $filters['rating_min'] = $request->rating_min;
        }

        if ($request->filled('rating_max')) {
            $satisfactions = $satisfactions->filter(function ($item) use ($request) {
                return $item->average_score <= $request->rating_max;
            });
            $filters['rating_max'] = $request->rating_max;
        }

        $pdf = PDF::loadView('satisfactions.all-pdf', compact('satisfactions', 'filters'));
        $pdf->setPaper('a4', 'landscape');
        return $pdf->download('semua-penilaian-kepuasan.pdf');
    }

    /**
     * Display the admin dashboard for survey results
     */
    public function dashboard()
    {
        // Hanya admin yang bisa akses
        // Memeriksa apakah pengguna adalah admin (misalnya memiliki is_admin = 1 di tabel users)
        if (!Auth::user()->is_admin) {
            abort(403, 'Unauthorized action.');
        }

        $satisfactions = Satisfaction::all();

        // Hitung rata-rata untuk setiap pertanyaan
        $averages = [];
        for ($i = 1; $i <= 15; $i++) {
            $field = "q$i";
            $averages[$field] = $satisfactions->avg($field);
        }

        // Hitung distribusi nilai untuk setiap pertanyaan
        $distributions = [];
        for ($i = 1; $i <= 15; $i++) {
            $field = "q$i";
            $distributions[$field] = [
                1 => $satisfactions->where($field, 1)->count(),
                2 => $satisfactions->where($field, 2)->count(),
                3 => $satisfactions->where($field, 3)->count(),
                4 => $satisfactions->where($field, 4)->count(),
                5 => $satisfactions->where($field, 5)->count(),
            ];
        }

        return view('satisfactions.dashboard', compact('satisfactions', 'averages', 'distributions'));
    }
}
