<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\EmailCampaignCreateRequest;
use App\Http\Requests\Admin\EmailCampaignDestroyRequest;
use App\Http\Requests\Admin\EmailCampaignEditRequest;
use App\Http\Requests\Admin\EmailCampaignIndexRequest;
use App\Http\Requests\Admin\EmailCampaignRecordsRequest;
use App\Http\Requests\Admin\EmailCampaignStoreRequest;
use App\Http\Requests\Admin\EmailCampaignUpdateRequest;
use App\Models\EmailCampaign;
use App\Models\EmailMarketingList;
use App\Models\Language;
use App\Traits\LogsAdminActivity;
use Illuminate\Http\JsonResponse;

class EmailCampaignController extends Controller
{
    use LogsAdminActivity;
    public function index(EmailCampaignIndexRequest $request)
    {
        $lists = EmailMarketingList::where('status', true)->orderBy('name')->get();

        return view('admin.email-campaigns.index', compact('lists'));
    }

    public function create(EmailCampaignCreateRequest $request)
    {
        $lists = EmailMarketingList::where('status', true)->orderBy('name')->get();
        $languages = Language::where('status', true)->get();

        return view('admin.email-campaigns.create', compact('lists', 'languages'));
    }

    public function store(EmailCampaignStoreRequest $request)
    {
        $validated = $request->validated();
        $campaign = EmailCampaign::create($validated);

        $this->logCreated($campaign, "Created email campaign #{$campaign->id} - {$campaign->name}");

        return redirect()->route('admin.email-campaigns.index')
            ->with('success', __('admin/email-campaigns.messages_created'));
    }

    public function edit(EmailCampaignEditRequest $request, EmailCampaign $emailCampaign)
    {
        $lists = EmailMarketingList::where('status', true)->orderBy('name')->get();
        $languages = Language::where('status', true)->get();

        return view('admin.email-campaigns.edit', [
            'campaign' => $emailCampaign,
            'lists' => $lists,
            'languages' => $languages,
        ]);
    }

    public function update(EmailCampaignUpdateRequest $request, EmailCampaign $emailCampaign)
    {
        $validated = $request->validated();
        $emailCampaign->update($validated);

        $this->logUpdated($emailCampaign, "Updated email campaign #{$emailCampaign->id} - {$emailCampaign->name}");

        return redirect()->route('admin.email-campaigns.index')
            ->with('success', __('admin/email-campaigns.messages_updated'));
    }

    public function records(EmailCampaignRecordsRequest $request): JsonResponse
    {
        $query = EmailCampaign::query();

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

        if ($request->filled('email_marketing_list_id')) {
            $query->where('email_marketing_list_id', $request->input('email_marketing_list_id'));
        }

        $query->orderBy('created_at', 'desc');

        $perPage = (int) $request->input('length', 25);
        $page = ($request->input('start', 0) / max($perPage, 1)) + 1;
        $paginator = $query->paginate($perPage, ['*'], 'page', $page);

        $data = collect($paginator->items())->map(function (EmailCampaign $c) {
            return [
                'id' => $c->id,
                'name' => $c->name,
                'subject' => $c->subject,
                'status' => $c->status,
                'email_marketing_list_id' => $c->email_marketing_list_id,
                'scheduled_at' => optional($c->scheduled_at)->toDateTimeString(),
                'sent_at' => optional($c->sent_at)->toDateTimeString(),
                'queued_count' => $c->queued_count,
                'sent_count' => $c->sent_count,
                'open_count' => $c->open_count,
                'click_count' => $c->click_count,
            ];
        })->all();

        return response()->json([
            'draw' => (int) $request->input('draw'),
            'recordsTotal' => $paginator->total(),
            'recordsFiltered' => $paginator->total(),
            'data' => $data,
        ]);
    }

    public function destroy(EmailCampaignDestroyRequest $request, EmailCampaign $emailCampaign)
    {
        $this->logDeleted($emailCampaign, "Deleted email campaign #{$emailCampaign->id} - {$emailCampaign->name}");

        $emailCampaign->delete();

        return response()->json(['success' => true]);
    }
}
