<?php

namespace App\Http\Controllers;

use App\Models\Complaint;
use App\Http\Requests\StoreComplaintRequest;
use App\Http\Requests\UpdateComplaintRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Barryvdh\DomPDF\Facade\PDF;

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

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('complaints.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'jenis_layanan' => 'required|string|max:255',
            'tanggal_keluhan' => 'required|date',
            'uraian_keluhan' => 'required|string',
            'saran' => 'required|string',
        ]);

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

        Complaint::create($data);

        return redirect()->route('complaints.index')
            ->with('success', 'Keluhan berhasil dikirimkan!');
    }

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

        return view('complaints.show', compact('complaint'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Complaint $complaint)
    {
        // Pastikan pengguna hanya bisa mengedit keluhannya sendiri
        if (Auth::user()->role === 'admin') {
            if ($complaint->user_id !== Auth::id()) {
                abort(403, 'Unauthorized action.');
            }
        }

        return view('complaints.edit', compact('complaint'));
    }

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

        $request->validate([
            'jenis_layanan' => 'required|string|max:255',
            'tanggal_keluhan' => 'required|date',
            'uraian_keluhan' => 'required|string',
            'saran' => 'required|string',
        ]);

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

        return redirect()->route('complaints.index')
            ->with('success', 'Keluhan berhasil diperbarui!');
    }

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

        $complaint->delete();

        return redirect()->route('complaints.index')
            ->with('success', 'Keluhan berhasil dihapus!');
    }

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

        $pdf = PDF::loadView('complaints.pdf', compact('complaint'));
        return $pdf->download('keluhan-' . $complaint->id . '.pdf');
    }

    /**
     * Generate PDF for all complaints (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
        $complaints = Complaint::latest()->get();

        // Jika ada filter, tambahkan ke array filters
        $filters = [];
        if ($request->filled('tanggal_mulai')) {
            $complaints = $complaints->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')) {
            $complaints = $complaints->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('jenis_layanan')) {
            $complaints = $complaints->filter(function ($item) use ($request) {
                return $item->jenis_layanan == $request->jenis_layanan;
            });
            $filters['jenis_layanan'] = $request->jenis_layanan;
        }

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