<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ActivityController extends Controller
{
    private function apiUrl($endpoint = '')
    {
        return rtrim(env('BACKEND_API_URL'), '/') . '/' . ltrim($endpoint, '/');
    }

    /**
     * FUNGSI DASHBOARD ADMIN
     */
    public function dashboard()
    {
        $response = Http::withToken(session('api_token'))
            ->acceptJson()
            ->get($this->apiUrl('/dashboard'));

        $stats = ['total' => 0, 'selesai' => 0, 'proses' => 0, 'users' => 0];
        $activities = [];

        if ($response->successful()) {
            $data = $response->json();
            if (isset($data['data']['stats'])) {
                $st = $data['data']['stats'];
                $stats['total']   = $st['total_tugas']    ?? 0;
                $stats['selesai'] = $st['status_selesai'] ?? 0;
                $stats['proses']  = $st['status_proses']  ?? 0;
            }
            if (isset($data['data']['recent_activities'])) {
                $activities = collect($data['data']['recent_activities'])->map(function($item) {
                    $petugasNames = 'System';
                    if (!empty($item['petugas']) && is_array($item['petugas'])) {
                        $names = [];
                        foreach ($item['petugas'] as $p) {
                            if (isset($p['username'])) {
                                $names[] = $p['username'];
                            } elseif (isset($p['name'])) {
                                $names[] = $p['name'];
                            }
                        }
                        if (!empty($names)) {
                            $petugasNames = implode(', ', $names);
                        }
                    }

                    return (object) [
                        'id'            => $item['id'],
                        'nama_kegiatan' => $item['kegiatan'],
                        'tanggal'       => $item['tanggal_mulai'],
                        'status'        => $item['status'] == 'proses' ? 'on_progres' : $item['status'],
                        'user'          => (object) ['name' => $petugasNames],
                        'keterangan'    => $item['keterangan'] ?? $item['kegiatan'] ?? '-',
                    ];
                });
            }
        }

        $topUsers        = [];
        $weeklyData      = [0, 0, 0, 0, 0, 0, 0];
        $divisionProgress = [
            ['name' => 'Operasional', 'pct' => 75, 'clr' => 'linear-gradient(90deg,#3b82f6,#6366f1)'],
            ['name' => 'IT',          'pct' => 45, 'clr' => 'linear-gradient(90deg,#a855f7,#ec4899)'],
            ['name' => 'SDM',         'pct' => 90, 'clr' => 'linear-gradient(90deg,#f97316,#f59e0b)'],
            ['name' => 'Keuangan',    'pct' => 64, 'clr' => 'linear-gradient(90deg,#22c55e,#10b981)'],
        ];

        return view('admin.dashboard', compact(
            'stats',
            'activities',
            'topUsers',
            'weeklyData',
            'divisionProgress'
        ));
    }

    /**
     * HALAMAN INDEX (DAFTAR KEGIATAN DENGAN FILTER)
     */
    public function index(Request $request)
    {
        $response = Http::withToken(session('api_token'))
            ->acceptJson()
            ->get($this->apiUrl('/penugasan'));

        $items = collect([]);
        if ($response->successful()) {
            $data  = $response->json();
            $items = collect($data['data'])->map(function($item) {
                $petugasNames = 'System';
                if (!empty($item['petugas']) && is_array($item['petugas'])) {
                    $names = [];
                    foreach ($item['petugas'] as $p) {
                        if (isset($p['username'])) {
                            $names[] = $p['username'];
                        } elseif (isset($p['name'])) {
                            $names[] = $p['name'];
                        }
                    }
                    if (!empty($names)) {
                        $petugasNames = implode(', ', $names);
                    }
                }

                return (object) [
                    'id'            => $item['id'],
                    'nama_kegiatan' => $item['kegiatan'],
                    'tanggal'       => $item['tanggal_mulai'],
                    'status'        => $item['status'] == 'proses' ? 'on_progres' : $item['status'],
                    'user'          => (object) ['name' => $petugasNames],
                ];
            });

            // Sembunyikan kegiatan yang sudah dibatalkan
            $items = $items->filter(function($item) {
                return $item->status !== 'dibatalkan';
            })->values();
        }

        // Simpan semua item sebelum filter untuk statistik
        $allItems = $items;

        // FILTER SEARCH
        if ($request->search) {
            $search = strtolower($request->search);
            $items  = $items->filter(function($item) use ($search) {
                return str_contains(strtolower($item->nama_kegiatan), $search) ||
                       str_contains(strtolower($item->user->name), $search);
            });
        }

        // FILTER STATUS
        if ($request->status && $request->status != 'semua') {
            $items = $items->filter(function($item) use ($request) {
                return $item->status === $request->status;
            });
        }

        // Manual Pagination
        $perPage     = 8;
        $currentPage = \Illuminate\Pagination\Paginator::resolveCurrentPage();
        $currentItems = $items->slice(($currentPage - 1) * $perPage, $perPage)->all();
        $activities   = new \Illuminate\Pagination\LengthAwarePaginator($currentItems, count($items), $perPage, $currentPage, [
            'path'  => \Illuminate\Pagination\Paginator::resolveCurrentPath(),
            'query' => $request->query(),
        ]);

        $divisis = collect(['-']);

        return view('admin.kegiatan.index', compact('activities', 'divisis', 'allItems'));
    }

    // DETAIL
    public function show($id)
    {
        $response = Http::withToken(session('api_token'))
            ->acceptJson()
            ->get($this->apiUrl('/penugasan/' . $id));

        if (!$response->successful()) {
            return redirect()->route('admin.kegiatan.index')->with('error', 'Data tidak ditemukan');
        }

        $data     = $response->json()['data'];
        $petugas  = collect($data['petugas'] ?? []);

        $petugasNames = 'System';
        if ($petugas->isNotEmpty()) {
            $names = [];
            foreach ($petugas as $p) {
                if (isset($p['username'])) {
                    $names[] = $p['username'];
                } elseif (isset($p['name'])) {
                    $names[] = $p['name'];
                }
            }
            if (!empty($names)) {
                $petugasNames = implode(', ', $names);
            }
        }

        $activity = (object) [
            'id'            => $data['id'],
            'nomor_surat'   => $data['nomor_surat'] ?? '-',
            'nama_kegiatan' => $data['kegiatan'],
            'tanggal'       => $data['tanggal_mulai'],
            'tanggal_selesai' => $data['tanggal_selesai'] ?? null,
            'lokasi'        => '-',
            'deskripsi'     => '-',
            'updated_at'    => $data['updated_at'] ?? now(),
            'status'        => $data['status'] == 'proses' ? 'on_progres' : $data['status'],
            'user'          => (object) ['name' => $petugasNames],
            'petugas'       => $petugas,
        ];

        return view('admin.kegiatan.detail', compact('activity'));
    }


}