<?php

namespace App\Http\Controllers;

use App\Models\AuditLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class AuditLogController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:view audit logs', ['only' => ['index']]);
        $this->middleware('permission:create audit logs', ['only' => ['create','store']]);
        $this->middleware('permission:update audit logs', ['only' => ['update','edit']]);
        $this->middleware('permission:delete audit logs', ['only' => ['destroy']]);
    }

   
    
public function index(Request $request)
{
    // 1️⃣ Get all table names from database for dropdown
    $tables = DB::select('SHOW TABLES');
    $databaseName = DB::connection()->getDatabaseName();

    $tableNames = [];
    foreach ($tables as $table) {
        $tableArray = (array)$table;
        $tableName = $tableArray['Tables_in_' . $databaseName];

        // Filter out unwanted tables
        if (!in_array($tableName, ['migrations', 'password_resets', 'personal_access_tokens'])) {
            $tableNames[] = $tableName;
        }
    }
    sort($tableNames); // Optional: alphabetical order

    // 2️⃣ Build base query with user relation
    $query = AuditLog::with('user');

    // 3️⃣ Search by description, table, or action
    if ($request->filled('search')) {
        $searchTerm = $request->search;
        $query->where(function ($q) use ($searchTerm) {
            $q->where('description', 'like', '%' . $searchTerm . '%')
              ->orWhere('table_name', 'like', '%' . $searchTerm . '%')
              ->orWhere('action', 'like', '%' . $searchTerm . '%');
        });
    }

    // 4️⃣ Filter by Table Name
    if ($request->filled('table_name')) {
        $query->where('table_name', $request->table_name);
    }

    // 5️⃣ Filter by Action
    if ($request->filled('action')) {
        $query->where('action', $request->action);
    }

    // 6️⃣ Filter by User
    if ($request->filled('user_id')) {
        $query->where('user_id', $request->user_id);
    }

    // 7️⃣ Filter by Date From
    if ($request->filled('date_from')) {
        $query->whereDate('created_at', '>=', $request->date_from);
    }

    // 8️⃣ Filter by Date To
    if ($request->filled('date_to')) {
        $query->whereDate('created_at', '<=', $request->date_to);
    }

    // 9️⃣ Paginate results - latest logs first
    $logs = $query->latest()->paginate(20)->withQueryString();

    // 10️⃣ Dropdown data for Actions (distinct)
    $actions = AuditLog::select('action')
                       ->distinct()
                       ->orderBy('action')
                       ->pluck('action');

    // 11️⃣ Dropdown data for Users
    $users = User::orderBy('name')->get();

    // 12️⃣ Return view with all data
    return view('audit-logs.index', compact(
        'logs',
        'tableNames',
        'actions',
        'users'
    ));
}

    // ... rest of your controller methods remain the same
    /**
     * Show Single Audit Log
     */
    public function show(AuditLog $auditLog)
    {
        $auditLog->load('user');
        return view('audit-logs.show', compact('auditLog'));
    }

    /**
     * Delete Audit Log (Admin Only)
     */
    public function destroy(AuditLog $auditLog)
    {
        if (!Auth::user()->hasRole(['admin', 'super-admin'])) {
            return redirect()
                ->route('audit-logs.index')
                ->with('error', 'You are not authorized to delete audit logs.');
        }

        $auditLog->delete();

        return redirect()
            ->route('audit-logs.index')
            ->with('success', 'Audit log deleted successfully.');
    }

    /**
     * Clear Logs Older Than 90 Days (Admin Only)
     */
    public function clearOldLogs()
    {
        if (!Auth::user()->hasRole(['admin', 'super-admin'])) {
            return redirect()
                ->route('audit-logs.index')
                ->with('error', 'You are not authorized to clear audit logs.');
        }

        $cutoffDate = now()->subDays(90);

        $deletedCount = AuditLog::where('created_at', '<', $cutoffDate)->delete();

        return redirect()
            ->route('audit-logs.index')
            ->with(
                'success',
                "Successfully cleared {$deletedCount} old audit logs (older than 90 days)."
            );
    }
}