<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Hash;

use App\Models\Profile;
use App\Models\User;
use App\Http\Resources\ProfileResource;

class ProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        Gate::authorize('fasilitator');

        $user = Auth::user();
        $profile = $user->profile;

        $desaKelurahanId = null;
        if ($profile->role === 'fasilitator') {
            $desaKelurahanId = $profile->desa_kelurahan_id;
        } 

        $size = $request->integer('size') ?: 10;

        $listProfile = Profile::when($request->search, function ($q, $search) {
                $search = strtolower($search);
                $q->whereRaw('lower(nama) like ?', ["%{$search}%"]);
            })
            ->when($desaKelurahanId ?? $request->desa_kelurahan_id, fn($q,$v) => $q->where('desa_kelurahan_id',$v))
            ->when($request->kecamatan_id, fn ($q, $v) =>
                $q->whereHas('desaKelurahan', fn ($k) =>
                    $k->where('kecamatan_id', $v)
                )
            )
            ->when($request->kabupaten_kota_id, fn ($q, $v) =>
                $q->whereHas('desaKelurahan.kecamatan', fn ($k) =>
                    $k->where('kabupaten_kota_id', $v)
                )
            )
            ->when($request->provinsi_id, fn ($q, $v) =>
                $q->whereHas('desaKelurahan.kecamatan.kabupatenKota', fn ($k) =>
                    $k->where('provinsi_id', $v)
                )
            );
        if ($request->filled('sort')) {
            $dir = str_starts_with($request->sort, '-') ? 'desc' : 'asc';
            $column = ltrim($request->sort, '-');

            $allowed = ['id', 'nama'];

            if (in_array($column, $allowed)) {
                $listProfile->orderBy($column, $dir);
            }
        } else {
            $listProfile->orderBy('nama', 'asc');
        }

        $listProfile = $listProfile->paginate($size);

        return ProfileResource::collection($listProfile);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        Gate::authorize('fasilitator');

        $validated = $request->validate([
            'nama' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'telepon' => ['nullable', 'string'],
            'alamat' => ['nullable', 'string'],
            'kk' => ['nullable', 'string'],
            'ktp' => ['nullable', 'string'],
            'file_kk' => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:2048'],
            'file_ktp' => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:2048'],
            'desa_kelurahan_id' => ['nullable', 'exists:master_desa_kelurahan,id'],
        ]);

        $user = User::create([
            'name' => $validated['nama'],
            'email' => $validated['email'],
            'password' => Hash::make('password123'), // Set default password or generate random
            'role' => 'petani',
            'email_verified_at' => now(),
            'created_by' => Auth::id(),
            'updated_by' => Auth::id(),
        ]);

        $profile = Profile::create([
            ...$validated,
            'user_id' => $user->id,
            'created_by' => Auth::id(),
            'updated_by' => Auth::id(),
        ]);

        return (new ProfileResource($profile))
            ->response()
            ->setStatusCode(201);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id): JSONResponse
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }

        $profile = Profile::with('desaKelurahan')->where('user_id', Auth::id())->first();
        return response()->json(new ProfileResource($profile));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id): JSONResponse
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }

        $user = Auth::user();
        if ($user->role === 'petani' && $user->profile->id != $id) {
            abort(403, 'Unauthorized');
        }
        
        $profile = Profile::findOrFail($id);

        if ($user->role === 'fasilitator' && $profile->desa_kelurahan_id != $user->profile->desa_kelurahan_id) {
            abort(403, 'Unauthorized');
        }

        $emailRule = Rule::unique('users', 'email')->ignore($profile->user_id);

        $validated = $request->validate([
            'nama' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', $emailRule],
            'telepon' => ['nullable', 'string'],
            'alamat' => ['nullable', 'string'],
            'kk' => ['nullable', 'string'],
            'ktp' => ['nullable', 'string'],
            'file_kk' => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:2048'],
            'file_ktp' => ['nullable', 'file', 'mimes:jpg,jpeg,png,pdf', 'max:2048'],
            'desa_kelurahan_id' => ['nullable', 'exists:master_desa_kelurahan,id'],
            'email_verified_at' => ['nullable', 'date'],
        ]);
        
        if ($request->hasFile('file_kk')) {
            $validated['file_kk'] = $request->file('file_kk')->getClientOriginalName();
            $kkPath = $request->file('file_kk')->store('uploads/profile/' . $profile->id, 'public');
            $validated['path_kk'] = $kkPath;
        }
        if ($request->hasFile('file_ktp')) {
            $validated['file_ktp'] = $request->file('file_ktp')->getClientOriginalName();
            $ktpPath = $request->file('file_ktp')->store('uploads/profile/' . $profile->id, 'public');
            $validated['path_ktp'] = $ktpPath;
        }

        $validated['updated_by'] = $user->id();

        DB::transaction(function () use ($profile, $user, $validated) {
            $profile->update($validated);
            $user->update([
                'name' => $validated['nama'],
                'email' => $validated['email'],
                'email_verified_at' => $validated['email_verified_at'],
                'updated_by' => $user->id,
            ]);
        });

        return response()->json($profile);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function downloadFile(string $id, string $type): JsonResponse | BinaryFileResponse
    {
        if (!Gate::any(['petani', 'fasilitator'])) {
            abort(403);
        }

        $profile = Profile::where('user_id', Auth::id())->first();

        if (!$profile) {
            return response()->json(['message' => 'Profile tidak ditemukan'], 404);
        }
        
        if ($type === 'kk' && $profile->path_kk) {
            return response()->file(storage_path('app/public/' . $profile->path_kk));
        } elseif ($type === 'ktp' && $profile->path_ktp) {
            return response()->file(storage_path('app/public/' . $profile->path_ktp));
        } else {
            return response()->json(['message' => 'File tidak ditemukan'], 404);
        }
    }
}
