<?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\AuditLog;
use App\Models\Opportunity;
use App\Models\Quote;
use App\Models\Signature;
use App\Models\User;
use App\Services\CommerceService;
use App\Services\DocumentStore;
use App\Services\NotificationService;
use App\Services\RecordService;

final class QuoteController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('quotes');
        $status = (string) ($_GET['status'] ?? 'draft');
        if (!in_array($status, ['all', 'draft', 'pending_approval', 'approved', 'sent', 'signed', 'rejected', 'void'], true)) {
            $status = 'draft';
        }
        $page = $this->page();
        $scope = $this->ownerScope();
        $assigned = (int) ($_GET['assigned'] ?? 0);
        $ownerFilter = $scope;
        if ($scope === null && $assigned > 0) {
            $ownerFilter = $assigned;
        }
        $accountId = (int) ($_GET['account'] ?? 0);
        $created = (string) ($_GET['created'] ?? 'all');
        if (!in_array($created, ['all', 'today', 'week', 'month'], true)) {
            $created = 'all';
        }
        $result = Quote::paginate($ownerFilter, $status, $this->q(), $page, 20, $accountId, $created);
        view('quotes/index', [
            'title' => 'Quotes',
            'rows' => $result['rows'],
            'total' => $result['total'],
            'page' => $page,
            'pages' => max(1, (int) ceil($result['total'] / 20)),
            'q' => $this->q(),
            'status' => $status,
            'assigned' => $assigned,
            'showAssigned' => $scope === null,
            'accountId' => $accountId,
            'created' => $created,
            'counts' => Quote::counts($ownerFilter),
            'accounts' => Account::allForSelect(),
            'owners' => User::salespeople((int) Auth::instance()->tenantId()),
            'notifications' => $this->notifications(),
        ]);
    }

    public function show(Request $request): void
    {
        $this->requireModule('quotes');
        $row = Quote::detail((int) $request->param('id'));
        if (!$row) {
            flash('error', 'Quote not found.');
            redirect('quotes');
        }
        view('quotes/show', [
            'title' => $row['number'],
            'row' => $row,
            'sign' => Signature::forRelated('quote', (int) $row['id']),
            'notifications' => $this->notifications(),
        ]);
    }

    public function store(Request $request): void
    {
        $this->requireModule('quotes');
        $this->verifyCsrf($request);
        $data = $request->all();
        $v = (new Validator())->required($data, ['account_id' => 'Account', 'title' => 'Title']);
        if ($v->fails()) {
            $this->fail($v);
        }
        $account = Account::find((int) $data['account_id']);
        if (!$account) {
            json_out(['ok' => false, 'error' => 'Account not found.'], 404);
        }
        $file = $_FILES['pdf'] ?? [];
        try {
            $fileName = DocumentStore::accept(is_array($file) ? $file : [], 'Upload a PDF for this quote.');
        } catch (\RuntimeException $e) {
            json_out(['ok' => false, 'error' => $e->getMessage()], 422);
        }
        $oppId = !empty($data['opportunity_id']) ? (int) $data['opportunity_id'] : null;
        if ($oppId && !Opportunity::find($oppId)) {
            $oppId = null;
        }
        $id = Quote::create([
            'account_id' => (int) $account['id'],
            'opportunity_id' => $oppId,
            'owner_id' => (int) Auth::instance()->id(),
            'number' => CommerceService::tempNumber(),
            'title' => $data['title'],
            'amount' => (float) ($data['amount'] ?? 0),
            'status' => 'draft',
            'body' => $data['body'] ?? '',
            'file_name' => $fileName,
        ]);
        try {
            DocumentStore::saveEntity('quote', $id, (string) $file['tmp_name']);
        } catch (\RuntimeException $e) {
            json_out(['ok' => false, 'error' => $e->getMessage()], 500);
        }
        CommerceService::assignNumber('quotes', $id, 'Q-');
        RecordService::logActivity('note', 'Quote created', (string) $data['title'], 'account', (int) $account['id']);
        AuditLog::write('quote.create', 'quote', $id);
        json_out(['ok' => true, 'id' => $id, 'redirect' => url('quotes/' . $id)]);
    }

    public function submit(Request $request): void
    {
        $this->requireModule('quotes');
        $this->verifyCsrf($request);
        $row = Quote::find((int) $request->param('id'));
        if (!$row) {
            json_out(['ok' => false, 'error' => 'Not found.'], 404);
        }
        if (!in_array($row['status'], ['draft', 'rejected'], true)) {
            json_out(['ok' => false, 'error' => 'This quote is already in review or sent.'], 422);
        }
        Quote::update((int) $row['id'], ['status' => 'pending_approval', 'reject_reason' => null]);
        foreach (User::managers((int) Auth::instance()->tenantId()) as $m) {
            NotificationService::send((int) $m['id'], 'Quote needs approval', (string) $row['title'], '/approvals');
        }
        AuditLog::write('quote.submit', 'quote', (int) $row['id']);
        json_out(['ok' => true, 'message' => 'Sent to the manager for approval.']);
    }

    public function send(Request $request): void
    {
        $this->requireModule('quotes');
        $this->verifyCsrf($request);
        $row = Quote::find((int) $request->param('id'));
        if (!$row) {
            json_out(['ok' => false, 'error' => 'Not found.'], 404);
        }
        if ($row['status'] !== 'approved') {
            json_out(['ok' => false, 'error' => 'A manager must approve this quote before you send it.'], 422);
        }
        Quote::update((int) $row['id'], ['status' => 'sent', 'sent_at' => date('Y-m-d H:i:s')]);
        try {
            CommerceService::shareQuote($row);
        } catch (\RuntimeException $e) {
            json_out(['ok' => false, 'error' => $e->getMessage()], 422);
        }
        RecordService::logActivity('note', 'Quote sent to customer', (string) $row['number'], 'account', (int) $row['account_id']);
        AuditLog::write('quote.send', 'quote', (int) $row['id']);
        json_out(['ok' => true, 'message' => 'Shared on the Customer Portal.']);
    }

    public function esign(Request $request): void
    {
        $this->requireModule('quotes');
        $this->verifyCsrf($request);
        $row = Quote::find((int) $request->param('id'));
        if (!$row) {
            json_out(['ok' => false, 'error' => 'Not found.'], 404);
        }
        if ($row['status'] === 'signed') {
            json_out(['ok' => false, 'error' => 'This quote is already signed.'], 422);
        }
        if ($row['status'] !== 'approved' && $row['status'] !== 'sent') {
            json_out(['ok' => false, 'error' => 'Approve the quote before asking for a signature.'], 422);
        }
        if ($row['status'] === 'approved') {
            Quote::update((int) $row['id'], ['status' => 'sent', 'sent_at' => date('Y-m-d H:i:s')]);
            try {
                CommerceService::shareQuote($row);
            } catch (\RuntimeException $e) {
                json_out(['ok' => false, 'error' => $e->getMessage()], 422);
            }
        }
        try {
            CommerceService::requestSignature(
                (int) $row['account_id'],
                'Sign quote ' . $row['number'],
                (string) ($row['body'] ?: $row['title']),
                'quote',
                (int) $row['id']
            );
        } catch (\RuntimeException $e) {
            json_out(['ok' => false, 'error' => $e->getMessage()], 422);
        }
        AuditLog::write('quote.esign', 'quote', (int) $row['id']);
        json_out(['ok' => true, 'message' => 'Signature request sent to the customer.']);
    }

    public function file(Request $request): void
    {
        $this->requireModule('quotes');
        $row = Quote::find((int) $request->param('id'));
        if (!$row || empty($row['file_name'])) {
            http_response_code(404);
            echo 'Not found.';
            return;
        }
        $tid = (int) Auth::instance()->tenantId();
        if (!DocumentStore::existsEntity($tid, 'quote', (int) $row['id'])) {
            http_response_code(404);
            echo 'No PDF on this quote.';
            return;
        }
        DocumentStore::streamEntity($tid, 'quote', (int) $row['id'], (string) $row['file_name']);
    }
}
