<?php

namespace App\Http\Controllers;

use App\Http\Requests\MailmoveRequest;
use App\Models\Mailmove;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MailMoveController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a paginated, filtered list of mailmove records.
     */
    public function index(Request $request): View
    {
        $query = Mailmove::query();

        if ($request->filled('search')) {
            $query->where('suser', 'like', '%' . $request->search . '%');
        }

        if ($request->filter === 'active') {
            $query->where('active', '>', 0)->orderBy('active', 'asc');
        } elseif ($request->filter === 'completed') {
            $query->where('active', '=', 0)->orderBy('id', 'desc');
        }
        else $query->orderBy('id', 'desc');

        $mailmoves = $query->withCount('logs')->paginate(20)->withQueryString();

        return view('mailmove.index', compact('mailmoves'));
    }

    /**
     * Show the form for creating a new mailmove record.
     */
    public function create(Request $request): View
    {
        $mailmove = new Mailmove();

        if ($request->filled('copy_from')) {
            $source = Mailmove::findOrFail($request->integer('copy_from'));
            $mailmove->fill($source->toArray());
        }

        return view('mailmove.create', compact('mailmove'));
    }

    /**
     * Store a newly created mailmove record.
     */
    public function store(MailmoveRequest $request): RedirectResponse
    {
        Mailmove::create($request->validated());

        return redirect()->route('mailmove.index')->with('success', 'Mailmove record created successfully.');
    }

    /**
     * Show the form for editing a mailmove record.
     */
    public function edit(Mailmove $mailmove): View
    {
        return view('mailmove.edit', compact('mailmove'));
    }

    /**
     * Update an existing mailmove record.
     */
    public function update(MailmoveRequest $request, Mailmove $mailmove): RedirectResponse
    {
        $mailmove->update($request->validated());

        return redirect()->route('mailmove.index')->with('success', 'Mailmove record updated successfully.');
    }
}
