<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ActivityController extends Controller
{
    /**
     * ==========================================
     * AREA USER (PENGAWAS / PETUGAS)
     * ==========================================
     */

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

    // 🔥 DASHBOARD USER
    public function index()
    {
        $response = \Illuminate\Support\Facades\Http::withToken(session('api_token'))
            ->get($this->apiUrl('/dashboard'));
        
        $activities = collect([]);
        $stats = ['status_proses' => 0, 'status_selesai' => 0];
        
        if ($response->successful()) {
            $data = $response->json();
            if (isset($data['data']['recent_activities'])) {
                // Mapping penugasan ke format yang diexpect view
                $activities = collect($data['data']['recent_activities'])->map(function($item) {
                    $petugasNames = [];
                    if(isset($item['petugas']) && is_array($item['petugas'])) {
                        foreach($item['petugas'] as $p) {
                            $petugasNames[] = $p['name'];
                        }
                    }
                    $assignedTo = !empty($petugasNames) ? implode(', ', $petugasNames) : (session('user_name') ?? 'Pegawai');

                    return (object) [
                        'id'            => $item['id'],
                        'nama_kegiatan' => $item['kegiatan'],
                        'tanggal'       => $item['tanggal_mulai'],
                        'tanggal_selesai' => $item['tanggal_selesai'] ?? null,
                        'status'        => $item['status'] == 'proses' ? 'on_progres' : $item['status'],
                        'lokasi'        => $item['lokasi'] ?? null,
                        'reviewed_at'   => $item['reviewed_at'] ?? null,
                        'user'          => (object) ['name' => $assignedTo],
                    ];
                });
            }
            if (isset($data['data']['stats'])) {
                $stats = $data['data']['stats'];
            }
        }

        $onProgres = $stats['status_proses'] ?? 0;
        $selesai = ($stats['status_selesai'] ?? 0) + ($stats['status_ditinjau'] ?? 0);

        // Ambil notifikasi
        $notifResponse = \Illuminate\Support\Facades\Http::withToken(session('api_token'))
            ->get($this->apiUrl('/notifications'));
        $notifications = [];
        if ($notifResponse->successful()) {
            $notifications = $notifResponse->json()['data'] ?? [];
        }

        $unreadCount = collect($notifications)->where('read_at', null)->count();

        return view('user.dashboard', compact(
            'activities',
            'onProgres',
            'selesai',
            'notifications',
            'unreadCount'
        ));
    }

    // 🔥 LIST SEMUA KEGIATAN USER
    public function list()
    {
        $response = \Illuminate\Support\Facades\Http::withToken(session('api_token'))
            ->get($this->apiUrl('/penugasan'));
            
        $activities = collect([]);
        if ($response->successful()) {
            $data = $response->json();
            $activities = collect($data['data'])->map(function($item) {
                $petugasNames = [];
                if(isset($item['petugas']) && is_array($item['petugas'])) {
                    foreach($item['petugas'] as $p) {
                        $petugasNames[] = $p['name'];
                    }
                }
                $assignedTo = !empty($petugasNames) ? implode(', ', $petugasNames) : (session('user_name') ?? 'Pegawai');

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

        return view('user.activity-list', compact('activities'));
    }

    // 🔥 SIMPAN ACTIVITY BARU
    public function store(Request $request)
    {
        $request->validate([
            'nama_kegiatan' => 'required|string|max:255',
            'tanggal'       => 'required|date',
            'lokasi'        => 'nullable|string|max:255',
            'deskripsi'     => 'nullable|string',
            'image'         => 'nullable|mimes:jpeg,png,jpg,pdf|max:2048',
        ]);

        $payload = [
            'nomor_surat' => null, // Tidak perlu generate karena ini laporan pegawai
            'kegiatan' => $request->nama_kegiatan,
            'tanggal_mulai' => $request->tanggal,
            'lokasi' => $request->lokasi,
            'keterangan' => $request->deskripsi,
            'status_note' => $request->status_note,
        ];

        $http = \Illuminate\Support\Facades\Http::withToken(session('api_token'));
        
        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $http = $http->attach('lampiran', file_get_contents($file), $file->getClientOriginalName());
            $payload['pegawai_ids[0]'] = session('user_id');
        } else {
            $payload['pegawai_ids'] = [session('user_id')];
        }

        $response = $http->post($this->apiUrl('/penugasan'), $payload);

        if ($response->successful()) {
            return redirect()->route('activity.list')->with('success', 'Kegiatan berhasil ditambahkan');
        }

        return back()->with('error', 'Gagal menambahkan kegiatan: ' . $response->json('message', 'Error API'));
    }

    // 🔥 DETAIL ACTIVITY
    public function show($id)
    {
        $response = \Illuminate\Support\Facades\Http::withToken(session('api_token'))
            ->get($this->apiUrl('/penugasan/' . $id));

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

        $data = $response->json()['data'];
        $activity = (object) [
            'id' => $data['id'],
            'nama_kegiatan' => $data['kegiatan'],
            'tanggal' => $data['tanggal_mulai'],
            'tanggal_selesai' => $data['tanggal_selesai'] ?? null,
            'lokasi' => $data['lokasi'] ?? '-',
            'deskripsi' => $data['keterangan'] ?? '-',
            'status_note' => $data['status_note'] ?? '-',
            'lampiran' => $data['lampiran'] ?? null,
            'updated_at' => $data['updated_at'] ?? now(),
            'status' => $data['status'] == 'proses' ? 'on_progres' : $data['status'],
            'user' => (object) ['name' => $data['pembuat']['name'] ?? session('user_name')],
            'progress' => $data['progress'] ?? [],
            'petugas' => $data['petugas'] ?? []
        ];

        return view('user.activity-detail', compact('activity'));
    }

    // 🔥 EDIT ACTIVITY
    public function edit($id)
    {
        $response = \Illuminate\Support\Facades\Http::withToken(session('api_token'))
            ->get($this->apiUrl('/penugasan/' . $id));

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

        $data = $response->json()['data'];
        
        $isPetugas = false;
        if(isset($data['petugas'])) {
            foreach($data['petugas'] as $p) {
                if($p['id'] == session('user_id')) {
                    $isPetugas = true;
                    break;
                }
            }
        }

        if (!$isPetugas) {
            return redirect()->route('activity.list')->with('error', 'Anda tidak memiliki hak untuk mengedit laporan ini.');
        }

        $activity = (object) [
            'id' => $data['id'],
            'nama_kegiatan' => $data['kegiatan'],
            'tanggal' => $data['tanggal_mulai'],
            'lokasi' => $data['lokasi'] ?? '',
            'deskripsi' => $data['keterangan'] ?? '',
            'status_note' => $data['status_note'] ?? '',
        ];

        return view('user.activity-edit', compact('activity'));
    }

    // 🔥 UPDATE ACTIVITY
    public function update(Request $request, $id)
    {
        $response = \Illuminate\Support\Facades\Http::withToken(session('api_token'))->get($this->apiUrl('/penugasan/' . $id));
        if ($response->successful()) {
            $data = $response->json()['data'];
            $isPetugas = false;
            if(isset($data['petugas'])) {
                foreach($data['petugas'] as $p) {
                    if($p['id'] == session('user_id')) {
                        $isPetugas = true;
                        break;
                    }
                }
            }
            if (!$isPetugas) {
                return redirect()->route('activity.list')->with('error', 'Anda tidak memiliki hak untuk mengedit laporan ini.');
            }
        }

        $request->validate([
            'nama_kegiatan' => 'required|string|max:255',
            'tanggal'       => 'required|date',
            'lokasi'        => 'nullable|string|max:255',
            'deskripsi'     => 'nullable|string',
            'image'         => 'nullable|mimes:jpeg,png,jpg,pdf|max:2048',
        ]);

        $payload = [
            'nomor_surat' => null, // Tidak perlu generate
            'kegiatan' => $request->nama_kegiatan,
            'tanggal_mulai' => $request->tanggal,
            'lokasi' => $request->lokasi,
            'keterangan' => $request->deskripsi,
            'status_note' => $request->status_note,
            // Laravel HTTP client sometimes fails PUT with multipart, we can simulate it with POST + _method=PUT
            '_method' => 'PUT',
        ];

        $http = \Illuminate\Support\Facades\Http::withToken(session('api_token'));
        
        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $http = $http->attach('lampiran', file_get_contents($file), $file->getClientOriginalName());
            $payload['pegawai_ids[0]'] = session('user_id');
        } else {
            $payload['pegawai_ids'] = [session('user_id')];
        }

        // Post with _method=PUT to handle multipart update safely
        $response = $http->post($this->apiUrl('/penugasan/' . $id), $payload);

        if ($response->successful()) {
            return redirect()->route('activity.detail', $id)
                ->with('success', 'Data berhasil diperbarui');
        }

        return back()->with('error', 'Gagal memperbarui: ' . $response->json('message'));
    }

    // 🔥 SELESAIKAN ACTIVITY
    public function selesai($id)
    {
        $responseCheck = \Illuminate\Support\Facades\Http::withToken(session('api_token'))->get($this->apiUrl('/penugasan/' . $id));
        if ($responseCheck->successful()) {
            $data = $responseCheck->json()['data'];
            $isPetugas = false;
            if(isset($data['petugas'])) {
                foreach($data['petugas'] as $p) {
                    if($p['id'] == session('user_id')) {
                        $isPetugas = true; break;
                    }
                }
            }
            if (!$isPetugas) {
                return redirect()->route('activity.list')->with('error', 'Anda tidak memiliki hak untuk menyelesaikan laporan ini.');
            }
        }

        $response = \Illuminate\Support\Facades\Http::withToken(session('api_token'))
            ->post($this->apiUrl("/penugasan/{$id}/update-status"), [
                'status' => 'selesai'
            ]);

        if ($response->successful()) {
            return back()->with('success', 'Kegiatan telah ditandai sebagai Selesai');
        }

        return back()->with('error', 'Gagal menandai selesai');
    }

    public function storeProgress(Request $request, $id)
    {
        $responseCheck = \Illuminate\Support\Facades\Http::withToken(session('api_token'))->get($this->apiUrl('/penugasan/' . $id));
        if ($responseCheck->successful()) {
            $data = $responseCheck->json()['data'];
            $isPetugas = false;
            if(isset($data['petugas'])) {
                foreach($data['petugas'] as $p) {
                    if($p['id'] == session('user_id')) {
                        $isPetugas = true; break;
                    }
                }
            }
            if (!$isPetugas) {
                return redirect()->route('activity.list')->with('error', 'Anda tidak memiliki hak untuk menambahkan progress pada laporan ini.');
            }
        }

        $request->validate([
            'note' => 'required|string',
            'attachment' => 'nullable|file|mimes:jpg,jpeg,png,pdf|max:2048'
        ]);

        $http = \Illuminate\Support\Facades\Http::withToken(session('api_token'));
        
        if ($request->hasFile('attachment')) {
            $file = $request->file('attachment');
            $http = $http->attach(
                'attachment',
                file_get_contents($file->getPathname()),
                $file->getClientOriginalName()
            );
        }

        $response = $http->post($this->apiUrl("/penugasan/{$id}/progress"), [
            'note' => $request->note,
        ]);

        if ($response->successful()) {
            return back()->with('success', 'Progres / Log pembaruan berhasil ditambahkan.');
        }

        return back()->with('error', 'Gagal menambahkan progres: ' . $response->json('message', 'Error'));
    }

    /**
     * ==========================================
     * AREA ADMIN (KASI / KABID)
     * ==========================================
     */

    public function adminDashboard()
    {
        $response = \Illuminate\Support\Facades\Http::withToken(session('api_token'))
            ->acceptJson()
            ->get($this->apiUrl('/dashboard'));

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

        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) + ($st['status_ditinjau'] ?? 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'],
                        'tanggal_selesai' => $item['tanggal_selesai'] ?? null,
                        'status' => $item['status'] == 'proses' ? 'on_progres' : $item['status'],
                        'user' => (object) ['name' => $petugasNames],
                        'keterangan' => $item['keterangan'] ?? $item['kegiatan'] ?? '-',
                        'status_note' => $item['status_note'] ?? null,
                        'lokasi' => $item['lokasi'] ?? '-',
                        'lampiran' => $item['lampiran'] ?? null
                    ];
                });
            }
        }

        // Mock data karena backend belum support
        $topUsers = [];
        $weeklyData = [0, 0, 0, 0, 0, 0, 0];
        $divisionProgress = [
            ['name' => 'Operasional', 'value' => 75, 'color' => '#378ADD'],
            ['name' => 'IT', 'value' => 45, 'color' => '#E24B4A'],
            ['name' => 'SDM', 'value' => 90, 'color' => '#EF9F27'],
        ];

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