<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\TicketPredefinedReplyCreateRequest;
use App\Http\Requests\Admin\TicketPredefinedReplyDestroyRequest;
use App\Http\Requests\Admin\TicketPredefinedReplyEditRequest;
use App\Http\Requests\Admin\TicketPredefinedReplyIndexRequest;
use App\Http\Requests\Admin\TicketPredefinedReplyRecordsRequest;
use App\Http\Requests\Admin\TicketPredefinedReplySearchRequest;
use App\Http\Requests\Admin\TicketPredefinedReplyStoreRequest;
use App\Http\Requests\Admin\TicketPredefinedReplyUpdateRequest;
use App\Models\TicketDepartment;
use App\Models\TicketPredefinedReply;
use App\Traits\LogsAdminActivity;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
use Spatie\Permission\Models\Role;

class TicketPredefinedReplyController extends Controller
{
    use LogsAdminActivity;
    /**
     * Display a listing of the resource.
     */
    public function index(TicketPredefinedReplyIndexRequest $request): View
    {
        return view('admin.ticket-predefined-replies.index');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(TicketPredefinedReplyCreateRequest $request): View
    {
        $departments = TicketDepartment::active()->get();
        $roles = Role::where('guard_name', 'admin')->get();

        return view('admin.ticket-predefined-replies.create', compact('departments', 'roles'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(TicketPredefinedReplyStoreRequest $request): RedirectResponse|JsonResponse
    {
        $validated = $request->validated();

        $predefinedReply = TicketPredefinedReply::create([
            'title' => $validated['title'],
            'content' => $validated['content'],
            'status' => $validated['status'] ?? true,
        ]);

        // Departman ilişkilerini kaydet
        if (isset($validated['department_ids']) && is_array($validated['department_ids'])) {
            $predefinedReply->ticketDepartments()->sync($validated['department_ids']);
        }

        // Rol ilişkilerini kaydet
        if (isset($validated['role_ids']) && is_array($validated['role_ids'])) {
            $predefinedReply->roles()->sync($validated['role_ids']);
        }

        // Çevirileri kaydet
        if (isset($validated['translations'])) {
            foreach ($validated['translations'] as $languageCode => $translation) {
                if (! empty($translation['title']) || ! empty($translation['content'])) {
                    $predefinedReply->setTranslation('title', $languageCode, $translation['title'] ?? '');
                    $predefinedReply->setTranslation('content', $languageCode, $translation['content'] ?? '');
                }
            }
            $predefinedReply->save();
        }

        $this->logCreated($predefinedReply, "Created predefined reply #{$predefinedReply->id} - {$predefinedReply->title}");

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => __('admin/ticket-predefined-replies.messages_created'),
                'redirect' => route('admin.ticket-predefined-replies.index'),
            ]);
        }

        return redirect()->route('admin.ticket-predefined-replies.index')
            ->with('success', __('admin/ticket-predefined-replies.messages_created'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(TicketPredefinedReplyEditRequest $request, TicketPredefinedReply $ticketPredefinedReply): View
    {
        $departments = TicketDepartment::active()->get();
        $roles = Role::where('guard_name', 'admin')->get();

        // Seçili departman ve rol ID'lerini al
        $selectedDepartmentIds = $ticketPredefinedReply->ticketDepartments()->pluck('ticket_departments.id')->toArray();
        $selectedRoleIds = $ticketPredefinedReply->roles()->pluck('roles.id')->toArray();

        return view('admin.ticket-predefined-replies.edit', compact('ticketPredefinedReply', 'departments', 'roles', 'selectedDepartmentIds', 'selectedRoleIds'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(TicketPredefinedReplyUpdateRequest $request, TicketPredefinedReply $ticketPredefinedReply): RedirectResponse|JsonResponse
    {
        $validated = $request->validated();

        $ticketPredefinedReply->update([
            'title' => $validated['title'],
            'content' => $validated['content'],
            'status' => $validated['status'] ?? true,
        ]);

        // Departman ilişkilerini güncelle
        if (isset($validated['department_ids']) && is_array($validated['department_ids'])) {
            $ticketPredefinedReply->ticketDepartments()->sync($validated['department_ids']);
        } else {
            $ticketPredefinedReply->ticketDepartments()->detach();
        }

        // Rol ilişkilerini güncelle
        if (isset($validated['role_ids']) && is_array($validated['role_ids'])) {
            $ticketPredefinedReply->roles()->sync($validated['role_ids']);
        } else {
            $ticketPredefinedReply->roles()->detach();
        }

        // Çevirileri güncelle
        if (isset($validated['translations'])) {
            foreach ($validated['translations'] as $languageCode => $translation) {
                if (! empty($translation['title']) || ! empty($translation['content'])) {
                    $ticketPredefinedReply->setTranslation('title', $languageCode, $translation['title'] ?? '');
                    $ticketPredefinedReply->setTranslation('content', $languageCode, $translation['content'] ?? '');
                }
            }
            $ticketPredefinedReply->save();
        }

        $this->logUpdated($ticketPredefinedReply, "Updated predefined reply #{$ticketPredefinedReply->id} - {$ticketPredefinedReply->title}");

        if ($request->expectsJson()) {
            return response()->json([
                'success' => true,
                'message' => __('admin/ticket-predefined-replies.messages_updated'),
                'redirect' => route('admin.ticket-predefined-replies.index'),
            ]);
        }

        return redirect()->route('admin.ticket-predefined-replies.index')
            ->with('success', __('admin/ticket-predefined-replies.messages_updated'));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(TicketPredefinedReplyDestroyRequest $request, TicketPredefinedReply $ticketPredefinedReply): JsonResponse
    {
        $this->logDeleted($ticketPredefinedReply, "Deleted predefined reply #{$ticketPredefinedReply->id} - {$ticketPredefinedReply->title}");

        $ticketPredefinedReply->delete();

        return response()->json([
            'success' => true,
            'message' => __('admin/ticket-predefined-replies.messages_deleted'),
        ]);
    }

    /**
     * Search predefined replies for quick insertion in ticket reply form.
     */
    public function search(TicketPredefinedReplySearchRequest $request): JsonResponse
    {
        $query = TicketPredefinedReply::active();

        // Search by title and content
        if ($request->filled('q')) {
            $searchValue = $request->input('q');
            $query->where(function ($q) use ($searchValue) {
                $q->where('title', 'like', "%{$searchValue}%")
                    ->orWhere('content', 'like', "%{$searchValue}%");
            });
        }

        // Filter by department (or include global replies with no department restriction)
        if ($request->filled('department_id')) {
            $query->forDepartment($request->input('department_id'));
        }

        $replies = $query->orderBy('title')
            ->limit(10)
            ->get(['id', 'title', 'content']);

        return response()->json([
            'data' => $replies->map(fn ($reply) => [
                'id' => $reply->id,
                'title' => $reply->getTranslation('title'),
                'content' => $reply->getTranslation('content'),
            ]),
        ]);
    }

    /**
     * Get records for DataTables.
     */
    public function records(TicketPredefinedReplyRecordsRequest $request): JsonResponse
    {
        $query = TicketPredefinedReply::with(['ticketDepartments', 'roles']);

        // Filtering
        if ($request->filled('search.value')) {
            $searchValue = $request->input('search.value');
            $query->where(function ($q) use ($searchValue) {
                $q->where('title', 'like', "%{$searchValue}%")
                    ->orWhere('content', 'like', "%{$searchValue}%");
            });
        }

        // Status filtering
        if ($request->filled('status')) {
            $query->where('status', $request->input('status'));
        }

        // Department filtering
        if ($request->filled('department_id')) {
            $query->whereHas('ticketDepartments', function ($q) use ($request) {
                $q->where('ticket_departments.id', $request->input('department_id'));
            });
        }

        // Role filtering
        if ($request->filled('role_id')) {
            $query->whereHas('roles', function ($q) use ($request) {
                $q->where('roles.id', $request->input('role_id'));
            });
        }

        // Total count
        $totalRecords = $query->count();

        // Ordering
        $orderColumnIndex = $request->input('order.0.column', 0);
        $orderDirection = $request->input('order.0.dir', 'desc');
        $orderColumns = ['id', 'title', 'departments', 'roles', 'status', 'created_at'];
        $orderColumn = $orderColumns[$orderColumnIndex] ?? 'id';

        if (in_array($orderColumn, ['departments', 'roles'])) {
            $orderColumn = 'id'; // Fallback to id for complex columns
        }

        $query->orderBy($orderColumn, $orderDirection);

        // Pagination
        $start = $request->input('start', 0);
        $length = $request->input('length', 10);
        $query->skip($start)->take($length);

        $records = $query->get();

        $data = $records->map(function ($record) {
            $departments = $record->ticketDepartments->pluck('name')->join(', ');
            $roles = $record->roles->pluck('name')->join(', ');

            return [
                'id' => $record->id,
                'title' => $record->title,
                'content' => \Str::limit($record->content, 100),
                'departments' => $departments ?: __('admin/ticket-predefined-replies.fields_all_departments'),
                'roles' => $roles ?: __('admin/ticket-predefined-replies.fields_all_roles'),
                'status' => $record->status,
                'created_at' => $record->created_at->format('d.m.Y H:i'),
            ];
        });

        return response()->json([
            'draw' => $request->input('draw'),
            'recordsTotal' => TicketPredefinedReply::count(),
            'recordsFiltered' => $totalRecords,
            'data' => $data,
        ]);
    }
}
