<?php

namespace App\Http\Controllers\Api;

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

class SalesmanMobileController extends Controller
{
    /**
     * LOGIN KHUSUS APLIKASI FLUTTER SALESMAN & SUPERVISOR
     */
    public function login(Request $request)
    {
        $request->validate([
            'login_id' => 'required',
            'password' => 'required',
        ]);

        $loginId = $request->login_id;

        // 1. Coba cari user berdasarkan Email ATAU Whatsapp langsung di tabel users
        $user = User::where('email', $loginId)
                    ->orWhere('whatsapp', $loginId)
                    ->first();

        // 2. Validasi kelayakan (Harus ketemu dan password benar)
        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json([
                'success' => false,
                'message' => 'Email/No. WA atau Password salah.'
            ], 401);
        }

        // 3. Pastikan rolenya adalah salesman ATAU supervisor_sales (SESUAI ROLES.SQL)
        if (!in_array($user->role, ['salesman', 'supervisor_sales'])) {
            return response()->json([
                'success' => false,
                'message' => 'Akses ditolak. Aplikasi ini khusus untuk Tim Sales dan Supervisor.'
            ], 403);
        }

        // PERBAIKAN ENTERPRISE: Pastikan user memiliki afiliasi cabang yang jelas
        if (!$user->branch_id) {
            return response()->json([
                'success' => false,
                'message' => 'Akun Anda belum terikat dengan cabang manapun. Hubungi Admin/HRD.'
            ], 403);
        }

        // 4. Ambil data detail salesman jika ada
        $salesmanDetail = DB::table('salesmen')->where('user_id', $user->id)->first();

        if ($user->role === 'salesman' && !$salesmanDetail) {
            return response()->json([
                'success' => false,
                'message' => 'Data detail salesman belum diatur oleh Admin. Hubungi HRD.'
            ], 403);
        }

        // Penentuan Identitas Spesifik Aplikasi (Untuk Navigasi Flutter Nanti)
        $salesmanType = 'TO'; // Default fallback
        if ($user->role === 'supervisor_sales') {
            $salesmanType = 'SUPERVISOR';
        } elseif ($salesmanDetail) {
            $salesmanType = $salesmanDetail->salesman_type; // 'TO' atau 'CANVAS'
        }

        // 5. Hapus token lama & Buat token baru (Mencegah multi-device login)
        $user->tokens()->delete();
        $token = $user->createToken('salesman_mobile_token')->plainTextToken;

        return response()->json([
            'success' => true,
            'message' => 'Login Berhasil',
            'data' => [
                'token' => $token,
                'user' => [
                    'id' => $user->id,
                    'salesman_id' => $salesmanDetail ? $salesmanDetail->id : null,
                    'name' => $user->name,
                    'email' => $user->email,
                    'phone' => $user->whatsapp ?? ($salesmanDetail->phone ?? ''), 
                    'branch_id' => $user->branch_id,
                    'role' => $user->role, // INJEKSI RBAC
                    'salesman_type' => $salesmanType // INJEKSI TIPE
                ]
            ]
        ], 200);
    }

    /**
     * GET PROFILE & STATISTIK HARI INI
     */
    public function getProfile(Request $request)
    {
        $user = $request->user();
        $salesman = DB::table('salesmen')->where('user_id', $user->id)->first();

        if (!in_array($user->role, ['salesman', 'supervisor_sales'])) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak.'], 403);
        }

        $visitedCount = 0;
        $today = Carbon::today()->toDateString();

        // Hitung statistik singkat hari ini sesuai wewenang
        if ($user->role === 'supervisor_sales') {
            // SPV melihat total kunjungan semua bawahan
            $bawahanIds = DB::table('salesmen')->where('supervisor_id', $user->id)->pluck('id');
            $visitedCount = DB::table('salesman_visits')
                ->whereIn('salesman_id', $bawahanIds)
                ->whereDate('visit_date', $today)
                ->count();
        } elseif ($salesman) {
            // Salesman melihat kunjungannya sendiri
            $visitedCount = DB::table('salesman_visits')
                ->where('salesman_id', $salesman->id)
                ->whereDate('visit_date', $today)
                ->count();
        }

        return response()->json([
            'success' => true,
            'data' => [
                'name' => $user->name,
                // Konsistensi dengan method login
                'phone' => $user->whatsapp ?? ($salesman->phone ?? ''),
                'today_visits' => $visitedCount,
                'role' => $user->role,
                'salesman_type' => $user->role === 'supervisor_sales' ? 'SUPERVISOR' : ($salesman->salesman_type ?? 'TO')
            ]
        ], 200);
    }

    /**
     * LOGOUT PERANGKAT
     */
    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json([
            'success' => true,
            'message' => 'Berhasil logout dari perangkat.'
        ], 200);
    }
}