<?php

namespace App\Http\Controllers\Api;

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

class AdminReportController extends Controller
{
    public function getLiveDashboardMetrics(Request $request)
    {
        try {
            $user = $request->user();
            $today = Carbon::today()->toDateString();

            // MODUL 1: DATA POSISI SPASIAL (Menggunakan Left Join agar tidak error jika data user belum sinkron)
            $salesmenPositionsQuery = DB::table('salesmen as s')
                ->leftJoin('users as u', 's.user_id', '=', 'u.id')
                ->select(
                    's.id as salesman_id',
                    'u.name as salesman_name',
                    's.last_latitude',
                    's.last_longitude',
                    's.last_activity_at'
                );

            // PENAMBAHAN: Isolasi Data Live Tracking Cabang
            if ($user && $user->role !== 'owner') {
                $salesmenPositionsQuery->where('u.branch_id', $user->branch_id);
            }

            $salesmenPositions = $salesmenPositionsQuery->get()
                ->map(function ($item) {
                    // Cek online dengan toleransi 30 menit (agar tidak mudah jadi offline)
                    $isOnline = false;
                    if ($item->last_activity_at) {
                        $isOnline = Carbon::parse($item->last_activity_at)->diffInMinutes(Carbon::now('Asia/Jakarta')) < 30;
                    }
                    $item->status_online = $isOnline ? 'ONLINE' : 'OFFLINE';
                    return $item;
                });

            // MODUL 2: KPI MONITORING
            $dayOfWeekMap = ['Monday' => 1, 'Tuesday' => 2, 'Wednesday' => 3, 'Thursday' => 4, 'Friday' => 5, 'Saturday' => 6, 'Sunday' => 7];
            $dayNum = $dayOfWeekMap[Carbon::now()->format('l')] ?? 1;

            $kpiQuery = DB::table('salesmen as s')
                ->join('users as u', 's.user_id', '=', 'u.id')
                ->select('s.id', 'u.name');

            // PENAMBAHAN: Isolasi Data Target & Realisasi Kunjungan (KPI) Cabang
            if ($user && $user->role !== 'owner') {
                $kpiQuery->where('u.branch_id', $user->branch_id);
            }

            $kpiPerformance = $kpiQuery->get()
                ->map(function ($sales) use ($dayNum, $today) {
                    $targetCount = DB::table('master_journey_plans')
                        ->where('salesman_id', $sales->id)
                        ->where('day_of_week', $dayNum)
                        ->where('is_active', 1)
                        ->count();

                    $realizationCount = DB::table('salesman_visits')
                        ->where('salesman_id', $sales->id)
                        ->where('visit_date', $today)
                        ->where('visit_status', 'completed')
                        ->count();

                    $deviationCount = DB::table('salesman_visits')
                        ->where('salesman_id', $sales->id)
                        ->where('visit_date', $today)
                        ->where('is_out_of_radius', 1)
                        ->count();

                    return [
                        'salesman_id' => $sales->id,
                        'salesman_name' => $sales->name,
                        'target_visit' => $targetCount,
                        'realization_visit' => $realizationCount,
                        'deviation_visit' => $deviationCount,
                        'achievement_percent' => $targetCount > 0 ? round(($realizationCount / $targetCount) * 100, 2) : 0.00
                    ];
                });

            // MODUL 3: ANALITIK NO-ORDER
            $noOrderQuery = DB::table('salesman_visits as sv')
                ->join('no_order_reasons as nor', 'sv.no_order_reason_id', '=', 'nor.id')
                // PERBAIKAN FATAL: Menambahkan join ke tabel salesmen terlebih dahulu sebelum ke users
                // agar relasi ID tidak tertukar yang berakibat pada kegagalan filter cabang
                ->join('salesmen as s', 'sv.salesman_id', '=', 's.id')
                ->join('users as u', 's.user_id', '=', 'u.id') 
                ->where('sv.visit_result', 'no_order')
                ->where('sv.visit_date', $today)
                ->select('nor.reason_name', DB::raw('COUNT(*) as total_cases'))
                ->groupBy('nor.id', 'nor.reason_name')
                ->orderBy('total_cases', 'desc');

            // PENAMBAHAN: Isolasi Data Analitik Penolakan Pembelian Cabang
            if ($user && $user->role !== 'owner') {
                $noOrderQuery->where('u.branch_id', $user->branch_id);
            }

            $noOrderAnalytics = $noOrderQuery->get();

            return response()->json([
                'success' => true,
                'data' => [
                    'live_positions' => $salesmenPositions,
                    'kpi_attendance' => $kpiPerformance,
                    'marketing_analytics' => $noOrderAnalytics
                ],
                'server_time' => Carbon::now('Asia/Jakarta')->toDateTimeString()
            ], 200);

        } catch (\Exception $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()], 500);
        }
    }
}