<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Sale;
use App\Models\SyncLog;
use Illuminate\Http\Request;
use Illuminate\View\View;

/**
 * Sync log — owner-facing audit trail of every cashier-complete
 * round-trip. Written by `SaleController::complete()` on every POST
 * that carries a `local_uuid`. Surfaces:
 *
 *   - successes (most rows)
 *   - failures (server-side rejections — bad payload, etc.)
 *   - conflicts (insufficient-stock, expired-batch, etc.)
 *
 * Slice 4 ships READ-ONLY visibility. Resolution actions
 * (acknowledge / void / create-adjustment) are a polish slice — most
 * conflicts are transient (cashier retries and it works) so the value
 * of action buttons is lower than the value of just *seeing* what
 * happened during an outage.
 *
 * Permission: `sync.log.view`.
 */
class SyncLogController extends Controller
{
    public function index(Request $request): View
    {
        abort_unless($request->user()?->hasPermission('sync.log.view'), 403);

        $result = (string) $request->query('result', '');
        $from   = $request->query('from');
        $to     = $request->query('to');
        $q      = trim((string) $request->query('q', ''));

        $logs = SyncLog::query()
            ->with(['user:id,name'])
            ->when(\in_array($result, ['success', 'failed', 'conflict'], true),
                fn ($qb) => $qb->where('result', $result))
            ->when($from, fn ($qb) => $qb->whereDate('synced_at', '>=', $from))
            ->when($to,   fn ($qb) => $qb->whereDate('synced_at', '<=', $to))
            ->when($q !== '', fn ($qb) => $qb->where(function ($w) use ($q) {
                $w->where('local_uuid', 'like', "%{$q}%")
                  ->orWhere('result_message', 'like', "%{$q}%");
            }))
            ->orderByDesc('synced_at')
            ->orderByDesc('id')
            ->limit(300)
            ->get();

        $counts = [
            'all'      => SyncLog::query()->count(),
            'success'  => SyncLog::query()->success()->count(),
            'failed'   => SyncLog::query()->failed()->count(),
            'conflict' => SyncLog::query()->conflict()->count(),
        ];

        // Summary cards — reflect the current filter (computed from the
        // filtered set; `$counts` above stays global for the filter badges).
        $summaryCards = [
            ['label' => __('sync_log.summary.total'),    'value' => number_format($logs->count())],
            ['label' => __('sync_log.summary.success'),  'value' => number_format($logs->where('result', 'success')->count()), 'tone' => 'positive'],
            ['label' => __('sync_log.summary.conflict'), 'value' => number_format($logs->where('result', 'conflict')->count()), 'tone' => 'warning'],
            ['label' => __('sync_log.summary.failed'),   'value' => number_format($logs->where('result', 'failed')->count()), 'tone' => 'danger'],
        ];

        return view('admin.sync-log.index', [
            'logs'         => $logs,
            'summaryCards' => $summaryCards,
            'counts'       => $counts,
            'filters'      => compact('result', 'from', 'to', 'q'),
        ]);
    }

    public function show(Request $request, SyncLog $syncLog): View
    {
        abort_unless($request->user()?->hasPermission('sync.log.view'), 403);

        // If this log corresponds to a successful sale we can link to
        // it; pull the row so the show page can render a small KPI strip.
        $sale = $syncLog->synced_entity_id
            ? Sale::query()->find($syncLog->synced_entity_id)
            : null;

        return view('admin.sync-log.show', [
            'log'  => $syncLog->load('user:id,name'),
            'sale' => $sale,
        ]);
    }
}
