<?php

namespace App\Http\Controllers;

use App\Models\Assignment;
use App\Models\UserProfile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AssignmentController extends Controller
{
    public function store(Request $request, $id)
    {
        try {
            if (!Auth::check()) {
                return response()->json(['message' => 'Unauthorized'], 401);
            }

            $usrid = UserProfile::find($id);

            $validatedData = $request->validate([
                'title' => 'required',
                'desc' => 'required',
                'doc_opt' => 'nullable',
                'deadline' => 'required|date',
                'for' => 'array',
            ]);

            $validatedData['created_by'] = $usrid->id;
            $validatedData['status'] = 'TODO';

            if (empty($validatedData['for'])) {
                $validatedData['for'] = json_encode(['everyone']);
            } else {
                $forr = [];
                foreach ($validatedData['for'] as $id) {
                    $user = UserProfile::find($id);
                    if ($user) {
                        $forr[] = $user->id;
                    }
                }
                $validatedData['for'] = empty($forr) ? json_encode(['everyone']) : json_encode($forr);
            }
            // $validatedData['for'] = implode(',', $validatedData['for']);
            $agenda = Assignment::create($validatedData);

            return response()->json(['message' => 'Task created successfully', 'data' => $agenda], 201);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to create Task', 'error' => $e->getMessage()], 500);
        }
    }
    public function update(Request $request, $id)
    {
        try {
            Auth::check();

            $agenda = Assignment::findOrFail($id);

            if (!$agenda) {
                return response()->json(['message' => 'Task not found'], 404);
            }

            $validatedData = $request->validate([
                'title' => 'string',
                'desc' => 'string',
                'doc_opt' => 'nullable',
                'deadline' => 'date',
                'for' => 'array',
                'status' => 'string',
            ]);

            if (isset($validatedData['for'])) {
                $forr = [];
                foreach ($validatedData['for'] as $id) {
                    $user = UserProfile::find($id);
                    if ($user) {
                        $forr[] = $user->id;
                    }
                }
                $validatedData['for'] = empty($forr) ? json_encode(['everyone']) : json_encode($forr);
            }

            $agenda->update($validatedData);

            return response()->json(['message' => 'Task updated successfully', 'data' => $agenda], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to update Task', 'error' => $e->getMessage()], 500);
        }
    }
    public function updateBYST(Request $request, $id)
    {
        try {
            Auth::check();

            $agenda = Assignment::findOrFail($id);

            if (!$agenda) {
                return response()->json(['message' => 'Task not found'], 404);
            }

            $validatedData = $request->validate([
                'desc' => 'sometimes|string',
                'doc_opt' => 'nullable',
                'status' => 'sometimes|string',
            ]);

           

            $agenda->update($validatedData);

            return response()->json(['message' => 'Task updated successfully', 'data' => $agenda], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to update Task', 'error' => $e->getMessage()], 500);
        }
    }

    public function destroy($id)
    {
        try {
            Auth::check();

            $agenda = Assignment::findOrFail($id);

            if (!$agenda) {
                return response()->json(['message' => 'Task not found'], 404);
            }

            $agenda->delete();

            return response()->json(['message' => 'Task deleted successfully'], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to delete Task', 'error' => $e->getMessage()], 500);
        }
    }

    public function getAll()
    {
        try {
            $assignments = Assignment::all();
            return response()->json(['message' => 'All assignments retrieved successfully', 'assignments' => $assignments], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to retrieve assignments', 'error' => $e->getMessage()], 500);
        }
    }

    public function getAssignmentFor($id)
    {
        try {
            $assignment = Assignment::whereJsonContains('for', (int) $id)
                ->orWhereJsonContains('for', 'everyone')
                ->get();
            return response()->json(['message' => 'Assignment retrieved successfully', 'data' => $assignment], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Failed to retrieve assignment', 'error' => $e->getMessage()], 500);
        }
    }
}


