<?php

namespace App\Http\Controllers;

use App\Models\Service;
use App\Http\Requests\StoreServiceRequest;
use App\Http\Requests\UpdateServiceRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Barryvdh\DomPDF\Facade\Pdf;

class ServiceController extends Controller
{
    /**
     * Daftar biaya retribusi parameter air
     */
    private $hargaParameter = [
        'TDS' => 22000,
        'TSS' => 22000,
        'Kekeruhan' => 15000,
        'Suhu' => 3500,
        'Daya Hantar Listrik' => 12500,
        'pH' => 10500,
        'Amonia' => 37000,
        'DO' => 16000,
        'Nitrat' => 32000,
        'Nitrit' => 33500,
        'BOD' => 40000,
        'COD' => 58000,
        'Tembaga' => 50000,
        'Besi' => 51000,
        'Mangan' => 52800
    ];

    /**
     * Daftar biaya retribusi jarak pengambilan sampel
     */
    private $hargaJarak = [
        'jarak < 100km' => 273000,
        'jarak 100km - 150km' => 373000,
        'jarak > 150km' => 473000
    ];

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = Service::query();

        // Filter berdasarkan status
        if ($request->has('status') && $request->status != '') {
            $query->where('status', $request->status);
        }

        // Filter berdasarkan tanggal mulai
        if ($request->has('tanggal_mulai') && $request->tanggal_mulai != '') {
            $query->whereDate('tanggal_uji', '>=', $request->tanggal_mulai);
        }

        // Filter berdasarkan tanggal selesai
        if ($request->has('tanggal_selesai') && $request->tanggal_selesai != '') {
            $query->whereDate('tanggal_uji', '<=', $request->tanggal_selesai);
        }

        // Filter berdasarkan parameter
        if ($request->has('parameter') && $request->parameter != '') {
            $query->where('parameter', $request->parameter);
        }

        // Filter berdasarkan jenis pengujian air
        if ($request->has('pengujian_kualitas_air') && $request->pengujian_kualitas_air != '') {
            $query->where('pengujian_kualitas_air', $request->pengujian_kualitas_air);
        }

        if (Auth::user()->role === 'admin') {
            $services = $query->latest()->get();
        } else {
            $query->where('user_id', Auth::id());
            $services = $query->latest()->get();
        }

        return view('services.index', compact('services'));
    }

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

    /**
     * Mengambil biaya retribusi parameter berdasarkan parameter yang dipilih
     */
    private function hitungBiayaParameter($parameter)
    {
        return $this->hargaParameter[$parameter] ?? 0;
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'jenis_permintaan' => 'required',
            'tanggal_uji' => 'required|date',
            'parameter' => 'required',
            'pengujian_kualitas_air' => 'required',
            'total_sampel' => 'required|integer|min:1',
            'jarak_pengambilan_sampel' => 'required',
        ]);

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

        // Hitung biaya retribusi parameter dan jarak
        $data['biaya_retribusi_parameter'] = $this->hitungBiayaParameter($data['parameter']) * $data['total_sampel'];
        $data['biaya_retribusi_jarak'] = $this->hargaJarak[$data['jarak_pengambilan_sampel']] ?? 0;
        $data['biaya_retribusi'] = $data['biaya_retribusi_parameter'] + $data['biaya_retribusi_jarak'];

        Service::create($data);

        return redirect()->route('services.index')
            ->with('success', 'Permintaan layanan berhasil dibuat!');
    }

    /**
     * Display the specified resource.
     */
    public function show(Service $service)
    {
        // Pastikan pengguna hanya bisa melihat layanannya sendiri kecuali admin
        if (Auth::user()->role !== 'admin' && $service->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        return view('services.show', compact('service'));
    }

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

        return view('services.edit', compact('service'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Service $service)
    {
        // Pastikan pengguna hanya bisa mengupdate layanannya sendiri kecuali admin
        if (Auth::user()->role !== 'admin' && $service->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        $rules = [
            'jenis_permintaan' => 'required',
            'tanggal_uji' => 'required|date',
            'parameter' => 'required',
            'pengujian_kualitas_air' => 'required',
            'total_sampel' => 'required|integer|min:1',
            'jarak_pengambilan_sampel' => 'required',
        ];

        // Tambahkan validasi khusus untuk admin
        if (Auth::user()->role === 'admin') {
            $rules['status'] = 'required';
            $rules['tanggal_selesai_uji'] = 'nullable|date';
            $rules['biaya_retribusi_parameter'] = 'nullable|integer|min:0';
            $rules['biaya_retribusi_jarak'] = 'nullable|integer|min:0';
            $rules['biaya_retribusi'] = 'nullable|integer|min:0';

            // Validasi keterangan jika status Diterima atau Ditolak
            if (in_array($request->status, ['Diterima', 'Ditolak'])) {
                $rules['keterangan'] = 'required|string|min:5';
            } else {
                $rules['keterangan'] = 'nullable|string';
            }

            // Validasi file hasil uji jika ada
            if ($request->hasFile('file_hasil_uji')) {
                $rules['file_hasil_uji'] = 'file|mimes:pdf,doc,docx,png,jpg,jpeg|max:10240';
            }
        }

        $request->validate($rules);

        $data = $request->all();

        // Hitung biaya retribusi parameter dan jarak jika data parameter atau sampel berubah
        if ($service->parameter !== $data['parameter'] || $service->total_sampel !== (int) $data['total_sampel']) {
            $data['biaya_retribusi_parameter'] = $this->hitungBiayaParameter($data['parameter']) * $data['total_sampel'];
        }

        // Perbarui biaya retribusi jarak jika jarak berubah
        if ($service->jarak_pengambilan_sampel !== $data['jarak_pengambilan_sampel']) {
            $data['biaya_retribusi_jarak'] = $this->hargaJarak[$data['jarak_pengambilan_sampel']] ?? 0;
        }

        // Hitung total biaya
        if (
            isset($data['biaya_retribusi_parameter']) &&
            isset($data['biaya_retribusi_jarak']) &&
            $data['biaya_retribusi_parameter'] !== null &&
            $data['biaya_retribusi_jarak'] !== null
        ) {
            $data['biaya_retribusi'] = $data['biaya_retribusi_parameter'] + $data['biaya_retribusi_jarak'];
        } elseif (
            Auth::user()->role === 'admin' &&
            isset($data['biaya_retribusi_parameter']) &&
            isset($data['biaya_retribusi_jarak']) &&
            $data['biaya_retribusi_parameter'] !== null &&
            $data['biaya_retribusi_jarak'] !== null
        ) {
            // Jika admin mengisi biaya retribusi parameter dan jarak, hitung total biaya
            $data['biaya_retribusi'] = $data['biaya_retribusi_parameter'] + $data['biaya_retribusi_jarak'];
        }

        // Jika ada upload file hasil uji
        if ($request->hasFile('file_hasil_uji')) {
            $file = $request->file('file_hasil_uji');
            $fileName = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/hasil_uji'), $fileName);
            $data['file_hasil_uji'] = $fileName;
        }

        $service->update($data);

        return redirect()->route('services.index')
            ->with('success', 'Permintaan layanan berhasil diperbarui!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Service $service)
    {
        // Pastikan pengguna hanya bisa menghapus layanannya sendiri kecuali admin
        if (Auth::user()->role !== 'admin' && $service->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        $service->delete();

        return redirect()->route('services.index')
            ->with('success', 'Permintaan layanan berhasil dihapus!');
    }

    /**
     * Generate PDF for service details
     */
    public function generatePdf(Service $service)
    {
        // Pastikan pengguna hanya bisa melihat layanannya sendiri kecuali admin
        if (Auth::user()->role !== 'admin' && $service->user_id !== Auth::id()) {
            abort(403, 'Unauthorized action.');
        }

        $pdf = PDF::loadView('services.pdf', compact('service'));

        $fileName = 'Layanan_' . $service->id . '_' . date('Ymd') . '.pdf';

        return $pdf->download($fileName);
    }

    /**
     * Generate PDF for all services with filters
     */
    public function generateAllPdf(Request $request)
    {
        // Check if user is admin
        if (Auth::user()->role !== 'admin') {
            abort(403, 'Unauthorized action.');
        }

        $query = Service::with('user');
        $filters = [];

        // Apply filters
        if ($request->has('status') && $request->status != '') {
            $query->where('status', $request->status);
            $filters['status'] = $request->status;
        }

        if ($request->has('tanggal_mulai') && $request->tanggal_mulai != '') {
            $query->whereDate('tanggal_uji', '>=', $request->tanggal_mulai);
            $filters['tanggal_mulai'] = \Carbon\Carbon::parse($request->tanggal_mulai)->format('d M Y');
        }

        if ($request->has('tanggal_selesai') && $request->tanggal_selesai != '') {
            $query->whereDate('tanggal_uji', '<=', $request->tanggal_selesai);
            $filters['tanggal_selesai'] = \Carbon\Carbon::parse($request->tanggal_selesai)->format('d M Y');
        }

        if ($request->has('parameter') && $request->parameter != '') {
            $query->where('parameter', $request->parameter);
            $filters['parameter'] = $request->parameter;
        }

        if ($request->has('pengujian_kualitas_air') && $request->pengujian_kualitas_air != '') {
            $query->where('pengujian_kualitas_air', $request->pengujian_kualitas_air);
            $filters['pengujian_kualitas_air'] = $request->pengujian_kualitas_air;
        }

        $services = $query->latest()->get();

        $pdf = PDF::loadView('services.all-pdf', compact('services', 'filters'));
        $pdf->setPaper('a4', 'landscape');

        $fileName = 'Semua_Layanan_' . date('Ymd') . '.pdf';

        return $pdf->download($fileName);
    }
}
