<?php

namespace App\Http\Controllers\user;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Project;
use App\Models\Task;

class taskController extends Controller
{
    private function checkUser()
    {
        if (!Auth::check() && !session('is_user_logged_in')) {
            return redirect('/login');
        }
        if (Auth::check()) {
            $user = Auth::user();
            if ($user->role === 'Super Admin' || $user->role === 'Admin') {
                return redirect('/');
            }
        }
        return null;
    }

    public function index(Request $request)
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();
        $search = $request->query('search');
        $status = $request->query('status');

        $query = Task::with('project')->where('user_id', $user->id)->latest();

        if (!empty($status) && $status !== 'All') {
            $query->where('status', $status);
            if ($status === 'Completed') {
                $query->where(function($q) {
                    $q->where('is_verified', 0)->orWhereNull('is_verified');
                });
            }
        }

        if ($request->has('is_verified')) {
            $query->where('is_verified', $request->query('is_verified'));
        }

        if (!empty($search)) {
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('status', 'like', "%{$search}%")
                  ->orWhereHas('project', function($pq) use ($search) {
                      $pq->where('name', 'like', "%{$search}%");
                  });
            });
        }

        $perPage = (int) $request->query('per_page', 10);
        $tasks = $query->paginate($perPage > 0 ? $perPage : 10)->withQueryString();

        return view('user.task.task', compact('tasks', 'search', 'status', 'user', 'perPage'));
    }

    public function create()
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();
        $projects = Project::all();

        return view('user.task.addtask', compact('projects', 'user'));
    }

    public function store(Request $request)
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();

        if ($request->has('tasks') && is_array($request->input('tasks'))) {
            $request->validate([
                'tasks' => ['required', 'array'],
                'tasks.*.name' => ['required', 'string', 'max:255'],
                'tasks.*.project_id' => ['required', 'exists:projects,id'],
                'tasks.*.type' => ['required', 'string'],
                'tasks.*.status' => ['required', 'string'],
                //'tasks.*.link' => ['nullable', 'string'],
            ]);

            foreach ($request->tasks as $taskData) {
                Task::create([
                    'name' => $taskData['name'],
                    'project_id' => $taskData['project_id'],
                    'user_id' => $user->id,
                    'type' => $taskData['type'],
                    'status' => $taskData['status'],
                   // 'link' => $taskData['link'] ?? null,
                    'added_by' => 'User',
                ]);
            }
        } else {
            $data = $request->validate([
                'name' => ['required', 'string', 'max:255'],
                'project_id' => ['required', 'exists:projects,id'],
                'type' => ['required', 'string'],
                'status' => ['required', 'string'],
                //'link' => ['nullable', 'string'],
            ]);

            Task::create([
                'name' => $data['name'],
                'project_id' => $data['project_id'],
                'user_id' => $user->id,
                'type' => $data['type'],
                'status' => $data['status'],
               // 'link' => $data['link'] ?? null,
                'added_by' => 'User',
            ]);
        }

        return redirect()->route('user.tasks.index')->with('success', 'Task created successfully.');
    }

    public function edit($id)
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();
        $task = Task::findOrFail($id);

        if ($task->user_id !== $user->id) {
            return redirect()->route('user.tasks.index');
        }

        $projects = Project::all();

        return view('user.task.edittask', compact('task', 'projects', 'user'));
    }

    public function update(Request $request, $id)
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();
        $task = Task::findOrFail($id);

        if ($task->user_id !== $user->id) {
            return redirect()->route('user.tasks.index');
        }

        $data = $request->validate([
            'name'       => ['required', 'string', 'max:255'],
            'project_id' => ['required', 'exists:projects,id'],
            'type'       => ['required', 'string'],
            'link'       => ['nullable', 'string'],
            'photos.*'   => ['image', 'mimes:jpeg,png,jpg,gif,webp', 'max:5120'],
        ]);

        $photos = is_array($task->photos) ? $task->photos : [];
        if ($request->hasFile('photos')) {
            foreach ($request->file('photos') as $photo) {
                $path = $photo->store('tasks', 'public');
                $photos[] = $path;
            }
        }

        $task->update([
            'name'       => $data['name'],
            'project_id' => $data['project_id'],
            'type'       => $data['type'],
            'link'       => $data['link'] ?? null,
            'photos'     => $photos,
        ]);

        return redirect()->route('user.tasks.index')
            ->with('success', 'Task updated successfully.');
    }

    public function destroy($id)
    {
        if ($redir = $this->checkUser()) return $redir;

        $user = Auth::user();
        $task = Task::find($id);

        if ($task && $task->user_id === $user->id) {
            $task->delete();
        }

        return redirect()->route('user.tasks.index')
            ->with('success', 'Task deleted successfully.');
    }

    public function updateStatus(Request $request, $id)
    {
        $task = Task::find($id);
        if (!$task) {
            return response()->json(['success' => false, 'message' => 'Task not found'], 404);
        }
        
        if (!session('is_admin_logged_in') && (!Auth::check() || Auth::user()->id !== $task->user_id)) {
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 403);
        }

        $status = $request->input('status');
        if ($status === 'Complete') {
            $status = 'Completed';
        }
        if ($status === 'On Hold') {
            $status = 'Hold';
        }

        // if ($status === 'In Progress' && empty($task->start_date)) {
        //     $task->start_date = now()->format('Y-m-d');
        // }

        // if ($status === 'Completed' && empty($task->end_date)) {
        //     $task->end_date = now()->format('Y-m-d');
        // }

        if ($status === 'Completed') {

        if (empty($task->start_date)) {
            $task->start_date = now()->format('Y-m-d');
        }

        if (empty($task->end_date)) {
            $task->end_date = now()->format('Y-m-d');
        }
        }
        elseif ($status === 'In Progress' && empty($task->start_date)) {

        $task->start_date = now()->format('Y-m-d');
        }

        $task->status = $status;
        $task->save();

        return response()->json([
            'success' => true, 
            'message' => 'Status updated successfully',
            'start_date' => $task->start_date ? \Carbon\Carbon::parse($task->start_date)->format('d/m/Y') : '-',
            'end_date' => $task->end_date ? \Carbon\Carbon::parse($task->end_date)->format('d/m/Y') : '-'
        ]);
    }
    
    public function removePhoto(Request $request, $id)
    {
        if ($redir = $this->checkUser()) return response()->json(['success' => false, 'message' => 'Unauthorized'], 401);

        $user = Auth::user();
        $task = Task::find($id);

        if (!$task || $task->user_id !== $user->id) {
            return response()->json(['success' => false, 'message' => 'Task not found or unauthorized'], 404);
        }

        $photoToRemove = $request->input('photo');
        $photos = is_array($task->photos) ? $task->photos : [];
        
        if (($key = array_search($photoToRemove, $photos)) !== false) {
            unset($photos[$key]);
            
            // Re-index array
            $task->photos = array_values($photos);
            $task->save();

            // Optional: delete file from storage
            // \Illuminate\Support\Facades\Storage::disk('public')->delete($photoToRemove);

            return response()->json(['success' => true, 'message' => 'Photo removed successfully']);
        }

        return response()->json(['success' => false, 'message' => 'Photo not found in task'], 404);
    }
}
