<?php

namespace App\Http\Controllers;

use App\Models\Message;
use App\Models\Task;
use App\Models\TaskFile;
use App\Models\TaskHistory;
use App\Models\User;
use App\Models\SystemSetting;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

class DesignerController extends Controller
{
    public function dashboard(Request $request): View
    {
        $query = Task::where('designer_id', $request->user()->id);

        return view('designer.dashboard', [
            'stats' => [
                'Assigned Tasks' => (clone $query)->count(),
                'Pending Tasks' => (clone $query)->where('status', 'pending')->count(),
                'Today Tasks' => (clone $query)->whereDate('deadline', today())->count(),
                'Submitted Work' => (clone $query)->where('status', 'submitted')->count(),
                'Revision Tasks' => (clone $query)->whereIn('status', ['revision', 'revision_required'])->count(),
                'Completed Tasks' => (clone $query)->whereIn('status', ['approved', 'completed', 'delivered'])->count(),
            ],
            'tasks' => (clone $query)->latest()->take(8)->get(),
        ]);
    }

    public function tasks(Request $request): View
    {
        return view('designer.tasks', ['tasks' => Task::where('designer_id', $request->user()->id)->latest()->get()]);
    }

    public function showTask(Request $request, Task $task): View
    {
        abort_unless($task->designer_id === $request->user()->id, 403);

        return view('designer.task-show', ['task' => $task->load(['client', 'files', 'histories'])]);
    }

    public function submitWork(Request $request, Task $task): RedirectResponse
    {
        abort_unless($task->designer_id === $request->user()->id, 403);

        $data = $request->validate([
            'file_path' => ['required', 'file', 'mimes:'.SystemSetting::uploadExtensions(), 'max:'.SystemSetting::uploadLimitKilobytes()],
            'note' => ['nullable', 'string'],
        ]);

        TaskFile::create([
            'task_id' => $task->id,
            'uploaded_by' => $request->user()->id,
            'type' => 'submission',
            'file_path' => $request->file('file_path')->store('task-submissions', 'public'),
            'note' => $data['note'] ?? null,
        ]);

        $task->update(['status' => 'submitted']);
        TaskHistory::create(['task_id' => $task->id, 'user_id' => $request->user()->id, 'status' => 'submitted', 'note' => $data['note'] ?? 'Designer uploaded work.']);

        return back()->with('status', 'Work submitted.');
    }

    public function revisionTasks(Request $request): View
    {
        return view('designer.tasks', ['tasks' => Task::where('designer_id', $request->user()->id)->whereIn('status', ['revision', 'revision_required'])->latest()->get(), 'title' => 'Revision Tasks']);
    }

    public function completedTasks(Request $request): View
    {
        return view('designer.tasks', ['tasks' => Task::where('designer_id', $request->user()->id)->whereIn('status', ['approved', 'completed', 'delivered'])->latest()->get(), 'title' => 'Completed Tasks']);
    }

    public function submittedWork(Request $request): View
    {
        return view('designer.tasks', [
            'tasks' => Task::where('designer_id', $request->user()->id)->where('status', 'submitted')->latest()->get(),
            'title' => 'Submitted Work',
        ]);
    }

    public function messages(Request $request): View
    {
        return view('designer.messages', [
            'messages' => Message::where('sender_id', $request->user()->id)->orWhere('receiver_id', $request->user()->id)->latest()->get(),
        ]);
    }

    public function storeMessage(Request $request): RedirectResponse
    {
        $data = $request->validate(['subject' => 'required|string|max:255', 'body' => 'required|string']);
        $data['sender_id'] = $request->user()->id;
        $data['receiver_id'] = User::whereIn('role', ['super_admin', 'admin'])->value('id');
        Message::create($data);

        return back()->with('status', 'Message sent.');
    }

    public function profile(Request $request): View
    {
        return view('designer.profile', ['user' => $request->user()]);
    }

    public function updateProfile(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'password' => ['nullable', 'string', 'min:8', 'confirmed'],
        ]);

        if (! empty($data['password'])) {
            $data['password'] = Hash::make($data['password']);
        } else {
            unset($data['password']);
        }

        $request->user()->update($data);

        return back()->with('status', 'Profile updated.');
    }
}
