<?php

namespace App\Http\Controllers;

use App\Models\DataAnggotakl;
use App\Models\DataJemaat;
use App\Models\DataKl;
use App\Models\DataSektor;
use App\Models\DataStatus;
use App\Models\DataWilayah;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Exception;
use Illuminate\Http\Request;

class KeluargaController extends Controller
{
    public function index(Request $request){
        $user = Auth::user();
        $query = DataKl::query();

        // Role-based scoping
        if($user->isKetuaWilayah()){
            $sektorIds = DataSektor::where('id_wilayah', $user->wilayah_id)->pluck('id');
            $query->whereIn("SEKTOR", $sektorIds);
        } elseif($user->isKetuaSektor()){
            $query->where("SEKTOR", $user->sektor_id);
        }

        if($request->search){
            $query->where(function($q) use ($request) {
                $q->where("NAMA_KELUARGA","LIKE","%".$request->search."%")
                  ->orWhere("ID_KELUARGA","LIKE","%".$request->search."%");
            });
        }

        if($request->wilayah){
            $query->where("WILAYAH", $request->wilayah);
        }

        if($request->sektor){
            $query->where("SEKTOR", $request->sektor);
        }

        $query->orderBy("updated_at","DESC");

        $dataJemaat = $query->paginate();
        return response()->json(array('data' => $dataJemaat, 'user' => $user));
    }
    public function find(Request $request){
        $user = Auth::user();
        $dataJemaat = DataKl::find($request->id);

        // Scope check for non-admin roles
        if($user->isKetuaWilayah()){
            $sektorIds = DataSektor::where('id_wilayah', $user->wilayah_id)->pluck('id')->toArray();
            if(!in_array($dataJemaat->SEKTOR, $sektorIds)){
                return response()->json(['success' => false, 'message' => 'Akses ditolak'], 403);
            }
        } elseif($user->isKetuaSektor()){
            if($dataJemaat->SEKTOR != $user->sektor_id){
                return response()->json(['success' => false, 'message' => 'Akses ditolak'], 403);
            }
        }

        $dataJemaat->STATUS = DataStatus::find($dataJemaat->STATUS);
        $dataJemaat->WILAYAH = DataWilayah::find($dataJemaat->WILAYAH);
        $dataJemaat->SEKTOR = DataSektor::find($dataJemaat->SEKTOR);
        return response()->json(array('data' => $dataJemaat));
    }
    public function add(Request $request){
        $user = Auth::user();
        if(!$user->isAdmin()){
            return response()->json(['success' => false, 'message' => 'Akses ditolak. Hanya admin yang dapat menambah data.'], 403);
        }
        try{
            DataKl::create($request->all());
            return response()->json(array('success' => true, 'message' => 'Data Tersimpan'));
        } catch(Exception $ex){
            return response()->json(array('success' => false, 'message' => 'Gagal, error: ' . $ex->getMessage()), 400);
        }
    }
    public function update(Request $request){
        $user = Auth::user();
        if(!$user->isAdmin()){
            return response()->json(['success' => false, 'message' => 'Akses ditolak. Hanya admin yang dapat mengubah data.'], 403);
        }
        try{
            $update = DataKl::find($request->ID);
            $update->update($request->all());
            return response()->json(array('success' => true, 'message' => 'Data Tersimpan'));
        } catch(Exception $ex){
            return response()->json(array('success' => false, 'message' => 'Gagal, error: ' . $ex->getMessage()), 400);
        }
    }
    public function delete(Request $request){
        $user = Auth::user();
        if(!$user->isAdmin()){
            return response()->json(['success' => false, 'message' => 'Akses ditolak. Hanya admin yang dapat menghapus data.'], 403);
        }
        try{
            $update = DataKl::find($request->id);
            $update->delete();
            return response()->json(array('success' => true, 'message' => 'Data Terhapus'));
        } catch(Exception $ex){
            return response()->json(array('success' => false, 'message' => 'Gagal, error: ' . $ex->getMessage()), 400);
        }
    }
    public function getAnggota(Request $request){
        try{
            // $id_keluarga = DataKl::where('ID_KELUARGA', '=', $request->id)->ID_KELUARGA;
            $anggota = DataJemaat::where('ID_KELUARGA', '=', $request->id)->orderBy('PERAN')->paginate();
            return response()->json(array('data' => $anggota));
        } catch(Exception $ex){
            return response()->json(array('success' => false, 'message' => 'Gagal, error: ' . $ex->getMessage()), 400);
        }
    }
    public function anggotaAdd(Request $request){
        $user = Auth::user();
        if(!$user->isAdmin()){
            return response()->json(['success' => false, 'message' => 'Akses ditolak. Hanya admin yang dapat mengubah data.'], 403);
        }
        try{
            $update = DataJemaat::find($request->id);
            $update->update($request->all());
            return response()->json(array('success' => true, 'message' => 'Data Tersimpan'));
        } catch(Exception $ex){
            return response()->json(array('success' => false, 'message' => 'Gagal, error: ' . $ex->getMessage()), 400);
        }
    }
    public function anggotaDestroy(Request $request){
        $user = Auth::user();
        if(!$user->isAdmin()){
            return response()->json(['success' => false, 'message' => 'Akses ditolak. Hanya admin yang dapat mengubah data.'], 403);
        }
        try{
            $update = DataJemaat::find($request->id);
            $update->update($request->all());
            return response()->json(array('success' => true, 'message' => 'Data Terhapus'));
        } catch(Exception $ex){
            return response()->json(array('success' => false, 'message' => 'Gagal, error: ' . $ex->getMessage()), 400);
        }
    }
}
