<?php

namespace Modules\Lpj\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Modules\Lpj\Models\Teams;
use Modules\Lpj\Models\Regions;
use Illuminate\Support\Facades\DB;
use Modules\Lpj\Models\TeamsUsers;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\RedirectResponse;
use Modules\Usermanagement\Models\User;
use Modules\Lpj\Http\Requests\TeamsRequest;
use Modules\Lpj\Exports\TeamPenilaianExport;

class TeamsController extends Controller
{
    public $user;
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return view('lpj::teams.index');
    }

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

    $regionTeam = Teams::pluck('regions_id')->toArray();

    $regions = Regions::whereNotIn('id', $regionTeam)->get();

    $userTeam = TeamsUsers::pluck('user_id')->toArray();
    $usersWithRole = User::whereNotIn('id', $userTeam)
        ->with('roles') // Eager load roles
        ->get();

    $user = $usersWithRole->filter(function ($user) {
        return $user->roles->contains(function ($role) {
                return $role->name === 'surveyor' || $role->name === 'surveyor-penilai' || $role->name === 'senior-officer';
            });
    });

    return view('lpj::teams.form', compact('regions', 'user'));
}

    /**
     * Store a newly created resource in storage.
     */
    public function store(TeamsRequest $request)
    {
        $validate = $request->validated();

        DB::beginTransaction();
        try {
            $teams =  Teams::create($validate);

            $users = $request->input('user', []);

            // loop untuk insert data users ke tabel teams_users
            foreach ($users as $user) {
                TeamsUsers::create([
                    'teams_id' => $teams->id,
                    'user_id' => $user
                ]);
            }

            DB::commit();

            return redirect()
                ->route('basicdata.teams.index')
                ->with('success', 'Data saved successfully. ');
        } catch (Exception $e) {

            DB::rollBack();

            return redirect()
                ->route('basicdata.teams.create')
                ->with('error', 'Failed to save data. ');
        }
    }

    /**
     * Show the specified resource.
     */
    public function show($id)
    {
        return view('lpj::show');
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $teams = Teams::find($id);

        $regions = Regions::all();
        $usedUsers = TeamsUsers::where('teams_id', '!=', $id)->pluck('user_id')->toArray();
        $usersWithRole = User::whereNotIn('id', $usedUsers)
            ->with('roles')
            ->get();


        $user = $usersWithRole->filter(function ($user) {
                return $user->roles->contains(function ($role) {
                        return $role->name === 'surveyor' || $role->name === 'surveyor-penilai' || $role->name === 'senior-officer';
                    });
        });

        // Ambil user yang sudah ada di tim ini
        $selectedUsers = $teams->teamsUsers->pluck('user_id')->toArray();

        return view('lpj::teams.form', compact('teams', 'regions', 'user', 'selectedUsers'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(TeamsRequest $request, $id)
    {
        $validate = $request->validated();

        DB::beginTransaction();
        try {
            $teams = Teams::findOrFail($id);

            // Update data tim
            $teams->update($validate);
            $userIds = $request->input('user', []);

            $teams->teamsUsers()->delete();


            foreach ($userIds as $userId) {
                TeamsUsers::create([
                    'teams_id' => $teams->id,
                    'user_id' => $userId
                ]);
            }

            DB::commit();

            return redirect()
                ->route('basicdata.teams.index')
                ->with('success', 'Data updated successfully. ');
        } catch (Exception $e) {

            DB::rollBack();

            return redirect()
                ->route('basicdata.teams.create')
                ->with('error', 'Failed to update data. ');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        DB::beginTransaction();
        try {

            $teams = Teams::findOrFail($id);
            $teams->teamsUsers()->delete();

            // Hapus tim
            $teams->delete();

            DB::commit();

            echo json_encode(['success' => true, 'message' => 'Team has been deleted successfully']);
        } catch (Exception $e) {
            DB::rollBack();
            echo json_encode(['success' => false, 'message' => 'Failed to delete Team']);
        }
    }

    public function dataForDatatables(Request $request)
    {
        if (is_null($this->user) || !$this->user->can('teams.view')) {
            //abort(403, 'Sorry! You are not allowed to view users.');
        }

        // Inisialisasi query
        $query = Teams::select('teams.id as id', 'teams.name as team_name', 'regions.name as region_name')
            ->join('regions', 'teams.regions_id', '=', 'regions.id')
            ->leftJoin('teams_users', 'teams.id', '=', 'teams_users.teams_id')
            ->leftJoin('users', 'teams_users.user_id', '=', 'users.id')
            ->addSelect('users.id as user_id', 'users.name as user_name');
        



        // Filter pencarian
        if ($request->has('search') && !empty($request->get('search'))) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('teams.name', 'LIKE', "%$search%")
                    ->orWhere('regions.name', 'LIKE', "%$search%")
                    ->orWhere('users.name', 'LIKE', "%$search%");
            });
        }

        // Sorting
        if ($request->has('sortOrder') && !empty($request->get('sortOrder'))) {
            $order  = $request->get('sortOrder');
            $column = $request->get('sortField');
            $query->orderBy($column, $order);
        }

        // Hitung total records
        $totalRecords = $query->count();

        // Pagination
        $size = $request->get('size', 10);
        $page = $request->get('page', 1);
        $offset = ($page - 1) * $size;

        // Ambil data dengan pagination
        $data = $query->skip($offset)->take($size)->get();
        $filteredRecords = $data->count();
        $pageCount = ceil($totalRecords / $size);

        // Ambil ID pengguna dari hasil query
        $userIds = $data->pluck('user_id')->unique();

        // Ambil data pengguna dengan peran mereka
        $users = User::whereIn('id', $userIds)
            ->with('roles')
            ->get()
            ->keyBy('id');

        // Format data
        $formattedData = $data->groupBy('id')->map(function ($group) use ($users) {
            $team = $group->first();
            $team->user_team = $group->map(function ($item) use ($users) {
                $user = $users->get($item->user_id);
                return [
                    'nama' => $item->user_name,
                    'roles' => $user ? $user->roles->pluck('name')->toArray() : [],
                ];
            })->toArray();
            return $team;
        })->values();

        return response()->json([
            'draw'            => $request->get('draw'),
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredRecords,
            'pageCount'       => $pageCount,
            'page'            => $page,
            'totalCount'      => $totalRecords,
            'data'            => $formattedData
        ]);
    }




    public function export()
    {
        return Excel::download(new TeamPenilaianExport(), 'team-penilai.xlsx');
    }
}
