<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Service;
use App\Models\Complaint;
use App\Models\Satisfaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class AdminController extends Controller
{
    /**
     * Display admin dashboard with important statistics.
     */
    public function dashboard()
    {
        // Jumlah service berdasarkan status
        $serviceStats = Service::select('status', DB::raw('count(*) as total'))
            ->groupBy('status')
            ->get()
            ->pluck('total', 'status')
            ->toArray();

        // Pastikan semua status memiliki nilai, jika tidak ada datanya
        $allStatuses = ['Menunggu', 'Diterima', 'Diproses', 'Selesai', 'Ditolak'];
        foreach ($allStatuses as $status) {
            if (!isset($serviceStats[$status])) {
                $serviceStats[$status] = 0;
            }
        }

        // Total service
        $totalServices = Service::count();

        // Total pelanggan
        $totalCustomers = User::where('role', 'pelanggan')->count();

        // Total admin
        $totalAdmins = User::where('role', 'admin')->count();

        // Total keluhan
        $totalComplaints = Complaint::count();

        // Total kepuasan pelanggan
        $totalSatisfactions = Satisfaction::count();

        // Service terbaru 
        $latestServices = Service::with('user')
            ->latest()
            ->take(5)
            ->get();

        // Distribusi jenis permintaan
        $serviceTypes = Service::select('jenis_permintaan', DB::raw('count(*) as total'))
            ->groupBy('jenis_permintaan')
            ->get()
            ->pluck('total', 'jenis_permintaan')
            ->toArray();

        // Distribusi pengujian kualitas air
        $waterTestTypes = Service::select('pengujian_kualitas_air', DB::raw('count(*) as total'))
            ->groupBy('pengujian_kualitas_air')
            ->get()
            ->pluck('total', 'pengujian_kualitas_air')
            ->toArray();

        // Data untuk chart bulanan (jumlah service per bulan)
        $monthlyServices = Service::select(
            DB::raw('MONTH(created_at) as month'),
            DB::raw('YEAR(created_at) as year'),
            DB::raw('count(*) as total')
        )
            ->whereYear('created_at', date('Y'))
            ->groupBy('year', 'month')
            ->orderBy('year')
            ->orderBy('month')
            ->get();

        $chartData = [];
        for ($i = 1; $i <= 12; $i++) {
            $found = false;
            foreach ($monthlyServices as $item) {
                if ((int) $item->month === $i) {
                    $chartData[] = $item->total;
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $chartData[] = 0;
            }
        }

        return view('admin.dashboard', compact(
            'serviceStats',
            'totalServices',
            'totalCustomers',
            'totalAdmins',
            'totalComplaints',
            'totalSatisfactions',
            'latestServices',
            'serviceTypes',
            'waterTestTypes',
            'chartData'
        ));
    }

    /**
     * Display a listing of the admins.
     */
    public function index()
    {
        $admins = User::where('role', 'admin')->get();
        return view('admin.index', compact('admins'));
    }

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

    /**
     * Store a newly created admin in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:8|confirmed',
            'gender' => 'required|in:Laki-laki,Perempuan',
        ]);

        User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
            'gender' => $request->gender,
            'role' => 'admin',
        ]);

        return redirect()->route('admin.admins.index')
            ->with('success', 'Admin berhasil ditambahkan!');
    }

    /**
     * Show the form for editing the specified admin.
     */
    public function edit(User $admin)
    {
        return view('admin.edit', compact('admin'));
    }

    /**
     * Update the specified admin in storage.
     */
    public function update(Request $request, User $admin)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique('users')->ignore($admin->id),
            ],
            'gender' => 'required|in:Laki-laki,Perempuan',
        ]);

        $admin->update([
            'name' => $request->name,
            'email' => $request->email,
            'gender' => $request->gender,
        ]);

        // Jika password baru diisi, validasi password lama
        if ($request->filled('password')) {
            $request->validate([
                'current_password' => 'required|string',
                'password' => 'required|string|min:8|confirmed',
            ]);

            // Verifikasi password lama
            if (!Hash::check($request->current_password, $admin->password)) {
                return back()
                    ->withErrors(['current_password' => 'Password lama tidak sesuai'])
                    ->withInput();
            }

            $admin->update([
                'password' => Hash::make($request->password),
            ]);
        }

        return redirect()->route('admin.admins.index')
            ->with('success', 'Data admin berhasil diperbarui!');
    }

    /**
     * Remove the specified admin from storage.
     */
    public function destroy(User $admin)
    {
        // Pastikan admin yang login saat ini tidak menghapus dirinya sendiri
        if (auth()->id() === $admin->id) {
            return redirect()->route('admin.admins.index')
                ->with('error', 'Anda tidak dapat menghapus akun Anda sendiri!');
        }

        $admin->delete();

        return redirect()->route('admin.admins.index')
            ->with('success', 'Admin berhasil dihapus!');
    }
}