<?php

namespace App\Http\Controllers\Reports;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Audit;

class AuditTrailController extends Controller
{
    public function getAuditTrail(Request $request)
    {
        $limit = $request->get('limit', 100);
        
        $audit_trails = Audit::query()
            ->when($request->filled('norujukan'), fn($q) => $q->where('norujukan', $request->norujukan))
            ->when($request->filled('actions'), fn($q) => $q->where('actions', $request->actions))
            ->orderBy('created_at', 'desc')
            ->limit($limit)
            ->get();

        return response()->json($audit_trails);
    }

    public function AuditTrailOperasi(Request $request)
    {
        $date_first = $request->get('date', null);
        $date_till = $request->get('date_till', null);

        $audit_trails = Audit::query()
            ->where('kodcaw', 'operasi')
            ->whereDate('created_at', '>=', $date_first)
            ->whereDate('created_at', '<=', $date_till)
            ->orderBy('created_at', 'asc')
            ->get();

        $audit_trails->map(function ($audit) {
                // Convert from UTC to Malaysia timezone (UTC+8)
                $audit->created_at = $audit->created_at->format('Y-m-d H:i:s');
                
                // Get differences between old_data and new_data
                $old_data = json_decode($audit->old_data, true) ?? [];
                $new_data = json_decode($audit->new_data, true) ?? [];
                
                $differences = [];
                
                // Find changed fields
                foreach ($new_data as $key => $new_value) {
                    if ($key === 'tarikhupdate') continue;
                    
                    $old_value = $old_data[$key] ?? null;
                    if ($old_value !== $new_value) {
                        $differences[$key] = [
                            'old' => $old_value,
                            'new' => $new_value
                        ];
                    }
                }
                
                // Check for removed fields
                foreach ($old_data as $key => $old_value) {
                    if ($key === 'tarikhupdate') continue;
                    
                    if (!array_key_exists($key, $new_data)) {
                        $differences[$key] = [
                            'old' => $old_value,
                            'new' => null
                        ];
                    }
                }
                
                $audit->differences = $differences;
                return $audit;
            });

        return response()->json($audit_trails);
    }
}