<?php

namespace App\Livewire;

use App\Models\Contract;
use App\Models\AuditLog;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;

class AuditorDashboard extends Component
{
    public $totalContracts;
    public $auditedContracts;
    public $pendingAudits;
    public $approvedAudits;
    public $rejectedAudits;
    public $recentAudits = [];

    public function mount()
    {
        // Total Kontrak
        $this->totalContracts = Contract::count();
        
        // Total Audit (distinct contract_id dari audit_logs)
        $this->auditedContracts = AuditLog::where('module', 'contract')
            ->where('action', 'like', 'audit_%')
            ->distinct('data->contract_id')
            ->count('data->contract_id');
        
        // Audit Pending (kontrak yang belum diaudit) - PAKE MAP (FIX)
        $auditedIds = AuditLog::where('module', 'contract')
            ->whereIn('action', ['audit_approved', 'audit_rejected'])
            ->whereNotNull('data')
            ->get()
            ->map(function($log) {
                return $log->data['contract_id'] ?? null;
            })
            ->filter()
            ->values()
            ->toArray();
        
        $this->pendingAudits = Contract::whereNotIn('id', $auditedIds)->count();
        
        // Audit Approved
        $this->approvedAudits = AuditLog::where('module', 'contract')
            ->where('action', 'audit_approved')
            ->distinct('data->contract_id')
            ->count('data->contract_id');
        
        // Audit Rejected
        $this->rejectedAudits = AuditLog::where('module', 'contract')
            ->where('action', 'audit_rejected')
            ->distinct('data->contract_id')
            ->count('data->contract_id');

        // Recent Audit Activities
        $this->recentAudits = AuditLog::with(['user'])
            ->where('module', 'contract')
            ->whereIn('action', ['audit_approved', 'audit_rejected'])
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get()
            ->map(function($log) {
                return [
                    'id' => $log->id,
                    'action' => $log->action,
                    'contract_id' => $log->data['contract_id'] ?? null,
                    'contract_number' => $log->data['contract_number'] ?? null,
                    'notes' => $log->data['notes'] ?? null,
                    'user' => $log->user ? $log->user->name : null,
                    'created_at' => $log->created_at,
                ];
            })
            ->toArray();
    }

    public function render()
    {
        return view('livewire.auditor-dashboard');
    }
}