<?php

namespace App\Http\Controllers;

use App\Models\Alternatif;
use App\Models\MemberKelompokTani;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class AlternatifController extends Controller
{
    public function index()
    {
        $user = Auth::user();

        if ($user->role === 'super_admin') {
            $alternatifs = Alternatif::all();
        } elseif ($user->role === 'admin') {
            $member = MemberKelompokTani::where('user_id', $user->id)->first();
            if ($member) {
                $userIds = MemberKelompokTani::where('kelompok_tani_id', $member->kelompok_tani_id)->pluck('user_id');
                $alternatifs = Alternatif::whereIn('user_id', $userIds)->get();
            } else {
                $alternatifs = collect(); // tidak ada kelompok
            }
        } else {
            $alternatifs = Alternatif::where('user_id', $user->id)->get();
        }

        return view('admin.alternatif', [
            'alternatifs' => $alternatifs,
            'title' => 'Data Alternatif'
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama_lahan' => 'required|string|max:255'
        ]);

        $userId = Auth::id();
        if (!$userId) {
            return redirect()->back()->with('error', 'Anda harus login terlebih dahulu.');
        }

        Alternatif::create([
            'nama_lahan' => $request->nama_lahan,
            'user_id' => $userId,
        ]);

        return redirect()->back()->with('success', 'Alternatif berhasil ditambahkan.');
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'nama_lahan' => 'required|string|max:255'
        ]);

        $alternatif = Alternatif::findOrFail($id);
        $user = Auth::user();

        // Cek izin berdasarkan kelompok
        if ($user->role === 'super_admin') {
            // boleh update
        } elseif ($user->role === 'admin') {
            $adminGroup = MemberKelompokTani::where('user_id', $user->id)->first();
            $targetGroup = MemberKelompokTani::where('user_id', $alternatif->user_id)->first();

            if (!$adminGroup || !$targetGroup || $adminGroup->kelompok_tani_id !== $targetGroup->kelompok_tani_id) {
                abort(403, 'Anda tidak punya izin untuk mengedit alternatif ini.');
            }
        } elseif ($alternatif->user_id !== $user->id) {
            abort(403, 'Anda tidak punya izin untuk mengedit alternatif ini.');
        }

        $alternatif->update([
            'nama_lahan' => $request->nama_lahan
        ]);

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

    public function destroy($id)
    {
        $alternatif = Alternatif::findOrFail($id);
        $user = Auth::user();

        if ($user->role === 'super_admin') {
            // bisa hapus semua
        } elseif ($user->role === 'admin') {
            $adminGroup = MemberKelompokTani::where('user_id', $user->id)->first();
            $targetGroup = MemberKelompokTani::where('user_id', $alternatif->user_id)->first();

            if (!$adminGroup || !$targetGroup || $adminGroup->kelompok_tani_id !== $targetGroup->kelompok_tani_id) {
                abort(403, 'Tidak diizinkan menghapus alternatif ini.');
            }
        } elseif ($alternatif->user_id !== $user->id) {
            abort(403, 'Tidak diizinkan menghapus alternatif ini.');
        }

        $alternatif->delete();

        return redirect()->route('alternatif.index')->with('success', 'Alternatif berhasil dihapus.');
    }

    public function destroyAll()
    {
        $user = Auth::user();

        if ($user->role === 'super_admin') {
            DB::table('data_penilaian')->delete();
            DB::table('data_alternatifs')->delete();
        } elseif ($user->role === 'admin') {
            $member = MemberKelompokTani::where('user_id', $user->id)->first();
            if (!$member) return redirect()->back()->with('error', 'Kelompok tidak ditemukan.');

            $userIds = MemberKelompokTani::where('kelompok_tani_id', $member->kelompok_tani_id)->pluck('user_id');

            $altIds = Alternatif::whereIn('user_id', $userIds)->pluck('id');

            DB::table('data_penilaian')->whereIn('alternatif_id', $altIds)->delete();
            Alternatif::whereIn('id', $altIds)->delete();
        } else {
            $altIds = Alternatif::where('user_id', $user->id)->pluck('id');
            DB::table('data_penilaian')->whereIn('alternatif_id', $altIds)->delete();
            Alternatif::where('user_id', $user->id)->delete();
        }

        return redirect()->route('alternatif.index')->with('success', 'Data alternatif berhasil dihapus.');
    }
}
