<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\Validator;
use App\Models\Account;
use App\Models\Activity;
use App\Models\AuditLog;
use App\Models\CampaignRecipient;
use App\Models\Contact;
use App\Models\Opportunity;
use App\Models\Task;
use App\Models\User;

final class ContactController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('contacts');
        $page = $this->page();
        $type = (string) ($_GET['type'] ?? $_GET['status'] ?? 'all');
        if (!in_array($type, ['all', 'primary', 'email', 'bounced'], true)) {
            $type = 'all';
        }
        $result = Contact::paginate($this->q(), $page, 15, null, $type);
        view('contacts/index', [
            'title' => noun('contacts', 'Contacts'),
            'rows' => $result['rows'],
            'total' => $result['total'],
            'page' => $page,
            'pages' => max(1, (int) ceil($result['total'] / 15)),
            'q' => $this->q(),
            'type' => $type,
            'counts' => Contact::boardCounts(),
            'accounts' => Account::allForSelect(),
            'notifications' => $this->notifications(),
        ]);
    }

    public function show(Request $request): void
    {
        $this->requireModule('contacts');
        $id = (int) $request->param('id');
        $contact = Contact::detail($id);
        if (!$contact) {
            flash('error', 'Contact not found.');
            redirect('contacts');
        }
        $accountId = (int) $contact['account_id'];
        $colleagues = [];
        foreach (Contact::forAccount($accountId) as $row) {
            if ((int) $row['id'] !== $id) {
                $colleagues[] = $row;
            }
        }
        view('contacts/show', [
            'title' => trim($contact['first_name'] . ' ' . $contact['last_name']),
            'contact' => $contact,
            'timeline' => Activity::timeline('contact', $id),
            'colleagues' => $colleagues,
            'opportunities' => can_see('opportunities') ? Opportunity::forAccount($accountId) : [],
            'tasks' => Task::forRelated('contact', $id),
            'accountTasks' => Task::forRelated('account', $accountId),
            'campaign_mail' => can_see('campaigns') || can_see('contacts') ? CampaignRecipient::forContact($id) : [],
            'notifications' => $this->notifications(),
        ]);
    }

    public function store(Request $request): void
    {
        $this->requireModule('contacts');
        $this->verifyCsrf($request);
        $data = $request->all();
        $v = (new Validator())
            ->required($data, ['first_name' => 'First name', 'last_name' => 'Last name', 'account_id' => 'Account']);
        if (($data['email'] ?? '') !== '') {
            $v->email($data, 'email', 'Email');
        }
        if ($v->fails()) {
            $this->fail($v);
        }
        $id = Contact::create([
            'account_id' => (int) $data['account_id'],
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'] ?? null,
            'phone' => $data['phone'] ?? null,
            'title' => $data['title'] ?? null,
            'role_label' => $data['role_label'] ?? null,
            'owner_id' => Auth::instance()->id(),
            'is_primary' => !empty($data['is_primary']) ? 1 : 0,
        ]);
        AuditLog::write('contact.create', 'contact', $id);
        json_out(['ok' => true, 'id' => $id, 'redirect' => url('contacts/' . $id)]);
    }
}
