<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Request;
use App\Core\Validator;
use App\Models\EmailLog;
use App\Models\Integration;
use App\Services\RecordService;

final class EmailController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('emails');
        $page = $this->page();
        $scope = has_role('manager') ? null : $this->ownerScope();
        $q = $this->q();
        $status = (string) ($_GET['status'] ?? 'all');
        if (!in_array($status, ['all', 'sent', 'logged', 'failed', 'in', 'out'], true)) {
            $status = 'all';
        }
        $result = EmailLog::paginate($page, 20, $scope, $q, $status);
        view('emails/index', [
            'title' => 'Personal email',
            'rows' => $result['rows'],
            'total' => $result['total'],
            'page' => $page,
            'pages' => max(1, (int) ceil($result['total'] / 20)),
            'q' => $q,
            'status' => $status,
            'counts' => EmailLog::boardCounts($scope),
            'notifications' => $this->notifications(),
        ]);
    }

    public function store(Request $request): void
    {
        $this->requireModule('emails');
        $this->verifyCsrf($request);
        $data = $request->all();
        $v = (new Validator())
            ->required($data, ['to_email' => 'To', 'subject' => 'Subject'])
            ->email($data, 'to_email', 'To', false);
        if ($v->fails()) {
            $this->fail($v);
        }
        $uid = (int) \App\Core\Auth::instance()->id();
        $provider = null;
        if (Integration::isConnected($uid, 'outlook', 'email')) {
            $provider = 'outlook';
        } elseif (Integration::isConnected($uid, 'gmail', 'email')) {
            $provider = 'gmail';
        }
        $sent = false;
        if (config('mail.enabled')) {
            $sent = @mail(
                $data['to_email'],
                $data['subject'],
                (string) ($data['body'] ?? ''),
                'From: ' . (string) config('mail.from_address')
            );
        }
        RecordService::logEmail([
            'to_email' => $data['to_email'],
            'subject' => $data['subject'],
            'body' => $data['body'] ?? '',
            'related_type' => $data['related_type'] ?? null,
            'related_id' => $data['related_id'] ?? null,
            'provider' => $provider,
            'sent' => $sent,
        ]);
        json_out(['ok' => true, 'message' => $sent ? 'Email sent and saved.' : 'Email saved on the record.']);
    }
}
