<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\DataTables\SpeciesSurveysDataTable;
use App\Models\SpeciesSurvey;
use App\Models\User;
use App\Models\State;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SpeciesSurveyController extends Controller
{
    /**
     * Display a listing of the species surveys.
     *
     * @param SpeciesSurveysDataTable $dataTable
     * @return mixed
     */
    public function index(SpeciesSurveysDataTable $dataTable)
    {
        $totalSurveys = SpeciesSurvey::query()
            ->select('user_id', 'species_id', 'state_id', 'landing_center_id', 'created_at')
            ->groupBy('user_id', 'species_id', 'state_id', 'landing_center_id', 'created_at')
            ->get()
            ->count();
        
        // Count unique states and landing centers recorded in the surveys table
        $totalStates = SpeciesSurvey::query()->distinct()->get(['state_name'])->count();
        $totalLandingCenters = SpeciesSurvey::query()->distinct()->get(['landing_center_name'])->count();

        $states = State::orderBy('name', 'asc')->get();
        $speciesList = DB::table('speacies')->orderBy('name', 'asc')->get();
        $landingCenters = DB::table('landing_centers')->orderBy('name', 'asc')->get();
        $users = User::orderBy('name', 'asc')->get();

        return $dataTable->render('admin.species-surveys.index', compact(
            'totalSurveys',
            'totalStates',
            'totalLandingCenters',
            'states',
            'speciesList',
            'landingCenters',
            'users'
        ));
    }

    /**
     * Show the form for editing the specified species survey.
     *
     * @param int $id
     * @return \Illuminate\View\View
     */
    public function edit($id)
    {
        $speciesSurvey = SpeciesSurvey::findOrFail($id);
        $users = User::orderBy('name', 'asc')->get();
        $states = State::orderBy('name', 'asc')->get();
        $speciesList = DB::table('speacies')->orderBy('name', 'asc')->get();
        $landingCenters = DB::table('landing_centers')->orderBy('name', 'asc')->get();

        return view('admin.species-surveys.edit', compact('speciesSurvey', 'users', 'states', 'speciesList', 'landingCenters'));
    }

    /**
     * Update the specified species survey in storage.
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $id)
    {
        $validated = $request->validate([
            'species_name' => ['required', 'string', 'max:255'],
            'species_id' => ['required', 'integer'],
            'state_id' => ['required', 'exists:states,id'],
            'landing_center_name' => ['required', 'string', 'max:255'],
            'landing_center_id' => ['required', 'integer'],
            'user_id' => ['required', 'exists:users,id'],
            'gear_name' => ['required', 'string', 'max:255'],
            'image' => ['nullable', 'image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
        ]);

        $survey = SpeciesSurvey::findOrFail($id);

        $user = User::findOrFail($validated['user_id']);
        $state = State::findOrFail($validated['state_id']);

        // Find all surveys belonging to the same group before we save changes on the representative record
        $surveysInGroup = SpeciesSurvey::where('user_id', $survey->user_id)
            ->where('species_id', $survey->species_id)
            ->where('state_id', $survey->state_id)
            ->where('landing_center_id', $survey->landing_center_id)
            ->where('created_at', $survey->created_at)
            ->get();

        // Update the representative record (with potential new image replacement)
        $survey->species_name = $validated['species_name'];
        $survey->species_id = $validated['species_id'];
        $survey->state_id = $validated['state_id'];
        $survey->state_name = $state->name;
        $survey->landing_center_name = $validated['landing_center_name'];
        $survey->landing_center_id = $validated['landing_center_id'];
        $survey->user_id = $validated['user_id'];
        $survey->user_name = $user->name;
        $survey->gear_name = $validated['gear_name'];

        if ($request->hasFile('image')) {
            // Delete old image if it exists in public/uploads
            if ($survey->image && file_exists(public_path('uploads/' . $survey->image))) {
                @unlink(public_path('uploads/' . $survey->image));
            }

            $file = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads'), $filename);
            $survey->image = $filename;
            $survey->image_url = asset('uploads/' . $filename);
        }

        $survey->save();

        // Now, update all other records in the same group to keep their metadata in sync
        foreach ($surveysInGroup as $s) {
            if ($s->id === $survey->id) {
                continue;
            }
            $s->species_name = $validated['species_name'];
            $s->species_id = $validated['species_id'];
            $s->state_id = $validated['state_id'];
            $s->state_name = $state->name;
            $s->landing_center_name = $validated['landing_center_name'];
            $s->landing_center_id = $validated['landing_center_id'];
            $s->user_id = $validated['user_id'];
            $s->user_name = $user->name;
            $s->gear_name = $validated['gear_name'];
            $s->save();
        }

        return redirect()
            ->route('admin.species-surveys.index')
            ->with('message', 'Species survey record updated successfully.')
            ->with('alert-type', 'success');
    }

    /**
     * Remove the specified species survey from storage.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $survey = SpeciesSurvey::findOrFail($id);

        // Find all surveys belonging to the same group
        $surveysInGroup = SpeciesSurvey::where('user_id', $survey->user_id)
            ->where('species_id', $survey->species_id)
            ->where('state_id', $survey->state_id)
            ->where('landing_center_id', $survey->landing_center_id)
            ->where('created_at', $survey->created_at)
            ->get();

        foreach ($surveysInGroup as $s) {
            // Delete associated image file if it exists in public/uploads
            if ($s->image && file_exists(public_path('uploads/' . $s->image))) {
                @unlink(public_path('uploads/' . $s->image));
            }
            $s->delete();
        }

        return response()->json([
            'success' => true,
            'message' => 'Species survey records deleted successfully.'
        ]);
    }
}
