<?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\Order;
use App\Models\User;
use App\Services\CommerceService;
use App\Services\RecordService;

final class OrderController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('orders');
        $status = (string) ($_GET['status'] ?? 'open');
        if (!in_array($status, ['all', 'open', 'fulfilled', 'cancelled'], true)) {
            $status = 'open';
        }
        $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);
        $result = Order::paginate($ownerFilter, $status, $this->q(), $page, 20, $accountId);
        view('orders/index', [
            'title' => 'Orders',
            '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,
            'counts' => Order::counts($ownerFilter),
            'accounts' => Account::allForSelect(),
            'owners' => User::salespeople((int) Auth::instance()->tenantId()),
            'notifications' => $this->notifications(),
        ]);
    }

    public function store(Request $request): void
    {
        $this->requireModule('orders');
        $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);
        }
        $oppId = !empty($data['opportunity_id']) ? (int) $data['opportunity_id'] : null;
        if ($oppId && !Opportunity::find($oppId)) {
            $oppId = null;
        }
        $id = Order::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' => 'open',
            'ordered_at' => $data['ordered_at'] ?: date('Y-m-d'),
        ]);
        CommerceService::assignNumber('orders', $id, 'SO-');
        RecordService::logActivity('note', 'Order logged', (string) $data['title'], 'account', (int) $account['id']);
        AuditLog::write('order.create', 'order', $id);
        json_out(['ok' => true, 'message' => 'Order saved on the customer.']);
    }

    public function status(Request $request): void
    {
        $this->requireModule('orders');
        $this->verifyCsrf($request);
        $row = Order::find((int) $request->param('id'));
        if (!$row) {
            json_out(['ok' => false, 'error' => 'Not found.'], 404);
        }
        $st = (string) $request->input('status');
        if (!in_array($st, ['open', 'fulfilled', 'cancelled'], true)) {
            json_out(['ok' => false, 'error' => 'Invalid status.'], 422);
        }
        Order::update((int) $row['id'], ['status' => $st]);
        AuditLog::write('order.status', 'order', (int) $row['id'], ['status' => $st]);
        json_out(['ok' => true]);
    }
}
