<?php

namespace App\Http\Controllers\admin;

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

class taskController extends Controller
{
    private function checkAdmin()
    {
        if (!Auth::check() && !session('is_admin_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->checkAdmin()) return $redir;

        $search = $request->query('search');
        $status = $request->query('status');
        $user_id = $request->query('user_id');

        $query = Task::with(['project', 'user'])->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 (!empty($user_id) && $user_id !== 'All') {
            $query->where('user_id', $user_id);
        }

        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}%");
                  })
                  ->orWhereHas('user', function($uq) use ($search) {
                      $uq->where('name', 'like', "%{$search}%");
                  });
            });
        }

        $perPage = (int) $request->query('per_page', 10);
        $tasks = $query->paginate($perPage > 0 ? $perPage : 10)->withQueryString();
        // $users = User::whereNotIn('role', ['Super Admin', 'Admin'])->get();
        
        $users = User::whereNotIn('role', ['Super Admin', 'Admin'])
            ->withCount(['tasks' => function($q) use ($status, $request, $search) {
                if (!empty($status) && $status !== 'All') {
                    $q->where('status', $status);
                    if ($status === 'Completed') {
                        $q->where(function($sq) {
                            $sq->where('is_verified', 0)->orWhereNull('is_verified');
                        });
                    }
                }
                if ($request->has('is_verified')) {
                    $q->where('is_verified', $request->query('is_verified'));
                }
                if (!empty($search)) {
                    $q->where(function($sq) use ($search) {
                        $sq->where('name', 'like', "%{$search}%")
                          ->orWhere('status', 'like', "%{$search}%")
                          ->orWhereHas('project', function($pq) use ($search) {
                              $pq->where('name', 'like', "%{$search}%");
                          });
                    });
                }
            }])->get();

        return view('admin.tasks.tasks', compact('tasks', 'search', 'status', 'user_id', 'users', 'perPage'));
    }

    public function create()
    {
        if ($redir = $this->checkAdmin()) return $redir;
        
        $projects = Project::all();
        $users = User::whereNotIn('role', ['Super Admin', 'Admin'])->get();

        return view('admin.tasks.addtask', compact('projects', 'users'));
    }

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

        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.*.user_id' => ['required', 'exists:users,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' => $taskData['user_id'],
                    'type' => $taskData['type'],
                    'status' => $taskData['status'],
                    // 'link' => $taskData['link'] ?? null,
                    'added_by' => 'Admin',
                ]);
            }
        } else {
            $data = $request->validate([
                'name' => ['required', 'string', 'max:255'],
                'project_id' => ['required', 'exists:projects,id'],
                'user_id' => ['required', 'exists:users,id'],
                'type' => ['required', 'string'],
                'status' => ['required', 'string'],
                // 'link' => ['nullable', 'string'],
            ]);

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

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

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

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

        $projects = Project::all();
        $users = User::whereNotIn('role', ['Super Admin', 'Admin'])->get();

        return view('admin.tasks.edittask', compact('task', 'projects', 'users'));
    }

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

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

        $data = $request->validate([
            'name'        => ['required', 'string', 'max:255'],
            'project_id'  => ['required', 'exists:projects,id'],
            'user_id'     => ['required', 'exists:users,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'],
            'user_id'     => $data['user_id'],
            'type'        => $data['type'],
            'link'        => $data['link'] ?? null,
            'photos'      => $photos,
        ]);

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

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

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

        if ($task) {
            $task->delete();
        }

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

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

        $task = Task::find($id);
        if (!$task) {
            return response()->json(['success' => false, 'message' => 'Task not found'], 404);
        }

        $task->is_verified = true;
        $task->save();

        return response()->json(['success' => true, 'message' => 'Task verified successfully']);
    }
    
    public function removePhoto(Request $request, $id)
    {
        if ($redir = $this->checkAdmin()) return response()->json(['success' => false, 'message' => 'Unauthorized'], 401);

        $task = Task::find($id);
        if (!$task) {
            return response()->json(['success' => false, 'message' => 'Task not found'], 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);
    }
}
