<?php

namespace App\Http\Controllers\Api;

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

class AdminAuthController extends Controller
{
    public function login(Request $request)
    {
        $request->validate([
            'username' => 'required|string',
            'password' => 'required'
        ]);

        $user = User::with('branch')->where('username', $request->username)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json(['success' => false, 'message' => 'Username atau Kata Sandi salah.'], 401);
        }

        // Validasi Status Aktif Karyawan
        if (isset($user->is_active) && !$user->is_active) {
            return response()->json(['success' => false, 'message' => 'Akun Anda telah dinonaktifkan. Silakan hubungi Administrator.'], 403);
        }

        // Daftar Role Lengkap
        $allowedRoles = [
            'owner', 'admin', 'manager', 'supervisor_admin', 'supervisor_sales',
            'admin_sales', 'admin_gudang', 'kepala_gudang', 'kasir', 
            'salesman', 'driver', 'helper'
        ];

        if (!in_array(strtolower($user->role), $allowedRoles)) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak! Role Anda tidak terdaftar.'], 403);
        }

        // Proteksi Integritas Cabang (Pengecualian untuk Owner dan Super Admin)
        if (strtolower($user->role) !== 'owner' && strtolower($user->role) !== 'super_admin' && empty($user->branch_id)) {
            return response()->json(['success' => false, 'message' => 'Akses ditolak! Akun Anda belum dipetakan ke cabang operasional manapun.'], 403);
        }

        // Validasi Pemetaan Rekening Bank (Branch Mapping)
        $hasFinancialMapping = false;
        if (!empty($user->branch_id)) {
            $hasFinancialMapping = DB::table('branch_accounts')
                ->where('branch_id', $user->branch_id)
                ->where('is_active', 1)
                ->exists();
        } else if (in_array(strtolower($user->role), ['owner', 'super_admin'])) {
            $hasFinancialMapping = true;
        }

        // Generate Token Sanctum
        $token = $user->createToken('admin_token')->plainTextToken;
        $permissions = $user->getAllPermissions()->pluck('name');

        // =========================================================================
        // BIKIN COOKIE CERDAS (AUTO-ADAPT UNTUK LOCALHOST HTTP & HOSTING HTTPS)
        // =========================================================================
        $isProduction = env('APP_ENV') === 'production'; // Cek file .env Laravel

        $cookie = cookie(
            'admin_token', 
            $token, 
            1440,       // Durasi (1 Hari)
            '/',        // Path
            null,       // Domain
            $isProduction,                 // Secure: FALSE di Localhost, TRUE di Hosting
            true,                          // HttpOnly: HARUS TRUE (Anti-XSS)
            false,                         // Raw: FALSE
            $isProduction ? 'None' : 'Lax' // SameSite: 'Lax' di Localhost, 'None' di Hosting
        );

        return response()->json([
            'success' => true,
            'data' => [
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'username' => $user->username,
                    'role' => $user->role,
                    'branch_id' => $user->branch_id,
                    'branch_name' => $user->branch ? $user->branch->name : 'Pusat / Head Office',
                    'has_financial_mapping' => $hasFinancialMapping,
                    'permissions' => $permissions 
                ]
            ],
            'message' => 'Login berhasil'
        ])->withCookie($cookie);
    }

    public function logout(Request $request)
    {
        if ($request->user()) {
            $request->user()->currentAccessToken()->delete();
        }
        
        // Hapus cookie dengan rapi
        $cookie = Cookie::forget('admin_token');

        return response()->json(['success' => true, 'message' => 'Berhasil logout'])->withCookie($cookie);
    }

    public function switchBranch(Request $request)
    {
        $request->validate([
            'branch_id' => 'required|exists:branches,id'
        ]);

        $user = $request->user();

        // Validasi keamanan: Pastikan hanya Owner/Super Admin yang bisa pindah cabang
        if (!in_array(strtolower($user->role), ['owner', 'super_admin'])) {
            return response()->json([
                'success' => false,
                'message' => 'Akses ditolak: Anda tidak memiliki wewenang untuk pindah cabang.'
            ], 403);
        }

        // Update branch_id pengguna yang sedang login
        $user->branch_id = $request->branch_id;
        $user->save();

        return response()->json([
            'success' => true,
            'message' => 'Konteks cabang berhasil dipindahkan.',
            'data' => [
                'active_branch_id' => $user->branch_id
            ]
        ]);
    }
}