<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\AdminBaseController;
use App\ActivityLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema; // ✅ needed to check columns
use Yajra\DataTables\Facades\DataTables;

class ActivityLogController extends AdminBaseController
{
    public function __construct()
    {
        parent::__construct();

        $this->pageTitle = __('Activity Logs');
        $this->pageIcon  = 'fa fa-history';
        $this->data['pageTitle'] = $this->pageTitle;
    }

    public function index(Request $request)
    {
        return view('admin.logs.index', $this->data);
    }

    /**
     * DataTables JSON.
     * Columns: by | description | job_title | created_at
     * Filters: job (title), user (username/email/name), from_date, to_date
     */
    public function data(Request $request)
    {
        $query = ActivityLog::with('user')->latest();

        // ✅ Does users.username exist?
        $hasUsername = Schema::hasColumn('users', 'username');

        // ---- Filters ----
        // Job title (only for JobApplication logs)
        if ($request->filled('job')) {
            $term = trim($request->input('job'));
            if ($term !== '') {
                $appIds = DB::table('job_applications')
                    ->join('jobs', 'jobs.id', '=', 'job_applications.job_id')
                    ->where('jobs.title', 'like', '%' . $term . '%')
                    ->pluck('job_applications.id');

                $query->where('loggable_type', 'App\\JobApplication')
                    ->whereIn('loggable_id', $appIds);
            }
        }

        // User filter: username (if exists) OR email OR name
        if ($request->filled('user')) {
            $term = trim($request->input('user'));
            if ($term !== '') {
                $query->whereHas('user', function ($q) use ($term, $hasUsername) {
                    $q->where(function ($x) use ($term, $hasUsername) {
                        if ($hasUsername) {
                            $x->where('username', 'like', '%' . $term . '%')
                                ->orWhere('email', 'like', '%' . $term . '%')
                                ->orWhere('name',  'like', '%' . $term . '%');
                        } else {
                            $x->where('email', 'like', '%' . $term . '%')
                                ->orWhere('name',  'like', '%' . $term . '%');
                        }
                    });
                });
            }
        }

        // Date range
        if ($request->filled('from_date')) {
            $query->whereDate('created_at', '>=', $request->input('from_date'));
        }
        if ($request->filled('to_date')) {
            $query->whereDate('created_at', '<=', $request->input('to_date'));
        }

        // ---- application_status maps (labels + colors) ----
        static $statusMaps = null;
        if ($statusMaps === null) {
            $rows = DB::table('application_status')->select('id', 'status', 'color')->get();
            $labels = [];
            $colors = [];
            foreach ($rows as $row) {
                $labels[$row->id] = $row->status;
                $colors[$row->id] = $row->color ?: '#6c757d';
            }
            $statusMaps = ['labels' => $labels, 'colors' => $colors];
        }

        // Small per-request caches
        static $appInfoCache  = []; // [application_id => ['full_name' => ..., 'job_title' => ...]]
        static $jobTitleCache = []; // [job_id => 'Job Title']

        return DataTables::of($query)
            ->addIndexColumn()

            // Date
            ->editColumn('created_at', function ($r) {
                return optional($r->created_at)->format('Y-m-d H:i');
            })

            // By: username (if column exists & value present) → name → email → System
            ->addColumn('by', function ($r) use ($hasUsername) {
                if (!$r->user) return 'System';
                $u = $r->user;
                if ($hasUsername && !empty($u->username)) return $u->username;
                if (!empty($u->name))                    return $u->name;
                if (!empty($u->email))                   return $u->email;
                return 'User #' . $r->user_id;
            })

            // Job title column
            ->addColumn('job_title', function ($r) use (&$appInfoCache, &$jobTitleCache) {
                if ($r->loggable_type === 'App\\JobApplication') {
                    $id = $r->loggable_id;
                    if (!isset($appInfoCache[$id])) {
                        $row = DB::table('job_applications')
                            ->leftJoin('jobs', 'jobs.id', '=', 'job_applications.job_id')
                            ->where('job_applications.id', $id)
                            ->select('job_applications.full_name', 'jobs.title as job_title')
                            ->first();
                        $appInfoCache[$id] = [
                            'full_name' => $row->full_name ?? null,
                            'job_title' => $row->job_title ?? null,
                        ];
                    }
                    return $appInfoCache[$id]['job_title'] ?? '';
                }

                if ($r->loggable_type === 'App\\Job') {
                    $id = $r->loggable_id;
                    if (!isset($jobTitleCache[$id])) {
                        $jobTitleCache[$id] = DB::table('jobs')->where('id', $id)->value('title');
                    }
                    return $jobTitleCache[$id] ?? '';
                }

                return '';
            })

            // Action sentence
            ->addColumn('description', function ($r) use ($statusMaps, &$appInfoCache, &$jobTitleCache) {
                $model   = class_basename($r->loggable_type);
                $modelId = $r->loggable_id;

                $subject = "{$model} #{$modelId}";

                if ($r->loggable_type === 'App\\JobApplication') {
                    if (!isset($appInfoCache[$modelId])) {
                        $row = DB::table('job_applications')
                            ->leftJoin('jobs', 'jobs.id', '=', 'job_applications.job_id')
                            ->where('job_applications.id', $modelId)
                            ->select('job_applications.full_name', 'jobs.title as job_title')
                            ->first();
                        $appInfoCache[$modelId] = [
                            'full_name' => $row->full_name ?? null,
                            'job_title' => $row->job_title ?? null,
                        ];
                    }
                    $fullName = $appInfoCache[$modelId]['full_name'] ?? null;
                    if (!empty($fullName)) {
                        $subject .= ' — ' . e($fullName);
                    }
                }

                $field = $r->field === 'status_id' ? 'status' : ($r->field ?? 'field');

                $from = e($r->from);
                $to   = e($r->to);

                if ($r->field === 'status_id') {
                    $fromLabel = $statusMaps['labels'][$r->from] ?? $r->from;
                    $toLabel   = $statusMaps['labels'][$r->to]   ?? $r->to;
                    $fromColor = $statusMaps['colors'][$r->from] ?? '#6c757d';
                    $toColor   = $statusMaps['colors'][$r->to]   ?? '#6c757d';

                    $chip = function ($text, $bg) {
                        $bg = preg_match('/^(#|rgb|hsl)/i', (string) $bg) ? $bg : '#6c757d';
                        return '<span class="badge" style="background-color:'.$bg.';color:#fff;">'.e($text).'</span>';
                    };

                    $from = $chip($fromLabel, $fromColor);
                    $to   = $chip($toLabel,   $toColor);
                }

                return "{$subject} — {$field}: {$from} \u{2192} {$to}";
            })

            ->rawColumns(['description'])
            ->make(true);
    }
}
