<?php

namespace App\Http\Controllers;

use App\Models\ProjectTask;
use App\Models\ProjectTaskComment;
use App\Models\ProjectTaskTimeLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

class ProjectTaskController extends Controller
{
    /**
     * Get task details for modal
     */
    public function show(ProjectTask $task)
    {
        $task->load(['assignee', 'assigner', 'subtasks.assignee', 'comments.user', 'attachments', 'timeLogs.user']);
        return response()->json($task);
    }

    /**
     * Update task status (for Kanban)
     */
    public function updateStatus(Request $request, ProjectTask $task)
    {
        try {
            Log::info("Updating task {$task->id} status to: {$request->status}");
            $task->update([
                'status' => $request->status,
                'order' => $request->order ?? $task->order
            ]);

            return response()->json(['success' => true]);
        } catch (\Exception $e) {
            Log::error("Failed to update task status: " . $e->getMessage());
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }

    /**
     * Add comment to task
     */
    public function addComment(Request $request, ProjectTask $task)
    {
        $comment = $task->comments()->create([
            'user_id' => Auth::id(),
            'comment' => $request->comment
        ]);

        return response()->json($comment->load('user'));
    }

    /**
     * Log time for task
     */
    public function logTime(Request $request, ProjectTask $task)
    {
        $log = $task->timeLogs()->create([
            'user_id' => Auth::id(),
            'log_date' => $request->date ?? Carbon::today(),
            'hours' => $request->hours,
            'description' => $request->description
        ]);

        // Update actual_hours in project_tasks
        $task->increment('actual_hours', $request->hours);

        return response()->json($log->load('user'));
    }

    /**
     * Store new task
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'project_id' => 'required|exists:projects,id',
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'assigned_to' => 'nullable|exists:users,id',
            'priority' => 'required|in:low,medium,high',
            'due_date' => 'nullable|date',
        ]);

        $task = ProjectTask::create(array_merge($validated, [
            'assigned_by' => Auth::id(),
            'status' => 'todo'
        ]));

        return response()->json($task->load('assignee'));
    }
    public function update(Request $request, ProjectTask $task)
    {
        $validated = $request->validate([
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'assigned_to' => 'nullable|exists:users,id',
            'priority' => 'required|in:low,medium,high,critical',
            'status' => 'required|in:todo,in_progress,in_review,done',
            'due_date' => 'nullable|date',
            'estimated_hours' => 'nullable|numeric',
        ]);

        $task->update($validated);

        return response()->json(['success' => true, 'task' => $task->load('assignee')]);
    }

    public function destroy(ProjectTask $task)
    {
        $task->delete();
        return response()->json(['success' => true]);
    }
}
