<?php

namespace App\Http\Controllers\Api\Auditor;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Contract;
use App\Models\Contractor;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class AuditorController extends Controller
{
    /**
     * Get audit dashboard
     */
    public function dashboard(): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'auditor') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: auditor',
                ], 403);
            }

            $totalContracts = Contract::count();
            $completedContracts = Contract::where('status', 'completed')->count();
            $signedContracts = Contract::where('status', 'signed')->count();
            $executionContracts = Contract::where('status', 'execution')->count();
            $draftContracts = Contract::where('status', 'draft')->count();

            $totalValue = Contract::sum('value');

            // Audit logs summary
            $totalAudits = AuditLog::where('module', 'contract')->count();
            $approvedAudits = AuditLog::where('module', 'contract')
                ->where('action', 'audit_approved')
                ->count();
            $rejectedAudits = AuditLog::where('module', 'contract')
                ->where('action', 'audit_rejected')
                ->count();

            return response()->json([
                'success' => true,
                'data' => [
                    'contracts' => [
                        'total' => $totalContracts,
                        'completed' => $completedContracts,
                        'signed' => $signedContracts,
                        'execution' => $executionContracts,
                        'draft' => $draftContracts,
                        'total_value' => (float) $totalValue,
                        'total_value_formatted' => 'Rp ' . number_format($totalValue, 0, ',', '.'),
                    ],
                    'audits' => [
                        'total' => $totalAudits,
                        'approved' => $approvedAudits,
                        'rejected' => $rejectedAudits,
                    ],
                    'recent_audits' => AuditLog::where('module', 'contract')
                        ->with(['user'])
                        ->orderBy('created_at', 'desc')
                        ->limit(5)
                        ->get(),
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error get auditor dashboard: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil dashboard audit: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get audit logs
     */
    public function logs(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'auditor') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: auditor',
                ], 403);
            }

            $module = $request->input('module');
            $action = $request->input('action');
            $limit = $request->input('limit', 20);
            $startDate = $request->input('start_date');
            $endDate = $request->input('end_date');

            $query = AuditLog::with(['user'])
                ->orderBy('created_at', 'desc');

            if ($module) {
                $query->where('module', $module);
            }

            if ($action) {
                $query->where('action', $action);
            }

            if ($startDate) {
                $query->whereDate('created_at', '>=', $startDate);
            }

            if ($endDate) {
                $query->whereDate('created_at', '<=', $endDate);
            }

            $logs = $query->limit($limit)->get();

            return response()->json([
                'success' => true,
                'data' => $logs,
                'total' => $logs->count(),
            ]);
        } catch (\Exception $e) {
            Log::error('Error get audit logs: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil audit log: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Get audit detail for a contract
     */
    public function auditDetail(Contract $contract): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'auditor') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: auditor',
                ], 403);
            }

            $contract->load(['contractor', 'jobPackage', 'signatures', 'termins']);

            $logs = AuditLog::where('module', 'contract')
                ->where(function($query) use ($contract) {
                    $query->where('data->contract_id', $contract->id)
                          ->orWhere('data->contract_number', $contract->contract_number);
                })
                ->orderBy('created_at', 'desc')
                ->limit(20)
                ->get();

            $totalValue = Contract::sum('value');
            $totalContracts = Contract::count();
            $completedContracts = Contract::where('status', 'completed')->count();
            $signedContracts = Contract::where('status', 'signed')->count();

            return response()->json([
                'success' => true,
                'data' => [
                    'contract' => $contract,
                    'audit_logs' => $logs,
                    'statistics' => [
                        'total_contracts' => $totalContracts,
                        'total_value' => (float) $totalValue,
                        'total_value_formatted' => 'Rp ' . number_format($totalValue, 0, ',', '.'),
                        'completed_contracts' => $completedContracts,
                        'signed_contracts' => $signedContracts,
                    ],
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error get audit detail: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal mengambil detail audit: ' . $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Approve audit result
     */
    public function approveAudit(Request $request, Contract $contract): JsonResponse
    {
        try {
            $user = Auth::user();
            
            if ($user->role !== 'auditor') {
                return response()->json([
                    'success' => false,
                    'message' => 'Anda tidak memiliki akses. Required role: auditor',
                ], 403);
            }

            $request->validate([
                'status' => 'required|in:approved,rejected',
                'notes' => 'nullable|string',
            ]);

            AuditLog::create([
                'user_id' => $user->id,
                'action' => 'audit_' . $request->status,
                'module' => 'contract',
                'data' => [
                    'contract_id' => $contract->id,
                    'contract_number' => $contract->contract_number,
                    'status' => $request->status,
                    'notes' => $request->notes,
                ],
                'ip_address' => $request->ip(),
                'user_agent' => $request->userAgent(),
                'old_values' => ['status' => $contract->status],
                'new_values' => ['status' => $contract->status . '_audited'],
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Hasil audit berhasil disimpan',
                'data' => [
                    'contract_id' => $contract->id,
                    'status' => $request->status,
                    'notes' => $request->notes,
                    'audited_by' => $user->name,
                    'audited_at' => now()->toISOString(),
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error approve audit: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal menyetujui audit: ' . $e->getMessage(),
            ], 500);
        }
    }
}