<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\ClientAdmin;
use App\Models\MessageTemplate;
use App\Models\SmsLog;
use App\Models\CallLog;
use App\Models\PromotionLog;
use App\Models\SessionLog;
use App\Models\User;
use App\Models\UserSetting;
use App\Services\ExcelExportService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class ClientDashboardController extends Controller
{
    protected ExcelExportService $excelExportService;

    public function __construct(ExcelExportService $excelExportService)
    {
        $this->excelExportService = $excelExportService;
    }

    /**
     * Get current client admin.
     */
    protected function getCurrentClientAdmin(): ?ClientAdmin
    {
        return Auth::guard('client_admin')->user();
    }

    /**
     * Get current client.
     */
    protected function getCurrentClient(): ?Client
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        return $clientAdmin?->client;
    }

    // ============ AUTHENTICATION ============

    /**
     * Show the client admin login page.
     */
    public function showLogin()
    {
        // Redirect if already logged in
        if (Auth::guard('client_admin')->check()) {
            return redirect()->route('client.dashboard');
        }

        return view('client.auth.login');
    }

    /**
     * Process client admin login.
     */
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (Auth::guard('client_admin')->attempt($credentials, $request->boolean('remember'))) {
            $clientAdmin = Auth::guard('client_admin')->user();

            // Check if client admin can login
            if (!$clientAdmin->canLogin()) {
                Auth::guard('client_admin')->logout();
                return back()->withErrors([
                    'email' => $clientAdmin->getLoginDenialReason(),
                ])->onlyInput('email');
            }

            $request->session()->regenerate();
            $clientAdmin->recordLogin();

            return redirect()->intended(route('client.dashboard'));
        }

        return back()->withErrors([
            'email' => 'The provided credentials do not match our records.',
        ])->onlyInput('email');
    }

    /**
     * Logout client admin.
     */
    public function logout(Request $request)
    {
        Auth::guard('client_admin')->logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('client.login');
    }

    // ============ DASHBOARD ============

    /**
     * Show the client dashboard.
     */
    public function index()
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();

        $userIds = User::where('client_id', $client->id)->pluck('id');

        // Stats array for the view
        $stats = [
            'total_users' => User::where('client_id', $client->id)->count(),
            'approved_users' => User::where('client_id', $client->id)->approved()->count(),
            'pending_users' => User::where('client_id', $client->id)->pending()->count(),
            'rejected_users' => User::where('client_id', $client->id)->rejected()->count(),
            'active_users' => User::where('client_id', $client->id)->approved()->active()->count(),
            'client_admins' => ClientAdmin::where('client_id', $client->id)->count(),
            'total_templates' => MessageTemplate::where('client_id', $client->id)->count(),
            'active_templates' => MessageTemplate::where('client_id', $client->id)->active()->count(),

            // SMS stats
            'total_sms' => SmsLog::whereIn('user_id', $userIds)->smsChannel()->count(),
            'sms_sent' => SmsLog::whereIn('user_id', $userIds)->smsChannel()->where('status', 'sent')->count(),
            'sms_today' => SmsLog::whereIn('user_id', $userIds)->smsChannel()->whereDate('sent_at', Carbon::today())->count(),

            // WhatsApp stats
            'total_whatsapp' => SmsLog::whereIn('user_id', $userIds)->whatsappChannel()->count(),
            'whatsapp_sent' => SmsLog::whereIn('user_id', $userIds)->whatsappChannel()->where('status', 'sent')->count(),
            'whatsapp_today' => SmsLog::whereIn('user_id', $userIds)->whatsappChannel()->whereDate('sent_at', Carbon::today())->count(),

            // Combined messages
            'total_messages' => SmsLog::whereIn('user_id', $userIds)->count(),
            'messages_today' => SmsLog::whereIn('user_id', $userIds)->whereDate('sent_at', Carbon::today())->count(),

            // Call stats
            'total_calls' => CallLog::whereIn('user_id', $userIds)->count(),
            'calls_today' => CallLog::whereIn('user_id', $userIds)->whereDate('call_time', Carbon::today())->count(),
            'incoming_calls' => CallLog::whereIn('user_id', $userIds)->where('call_type', 'incoming')->count(),
            'outgoing_calls' => CallLog::whereIn('user_id', $userIds)->where('call_type', 'outgoing')->count(),
            'missed_calls' => CallLog::whereIn('user_id', $userIds)->where('call_type', 'missed')->count(),
        ];

        // Recent users
        $recentUsers = User::where('client_id', $client->id)
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        // Recent Messages (both SMS and WhatsApp)
        $recentMessages = SmsLog::whereIn('user_id', $userIds)
            ->with('user')
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Chart data - last 7 days (includes SMS, WhatsApp, Calls)
        $chartData = $this->getChartDataLast7Days($userIds);

        // Subscription info array
        $subscriptionInfo = [
            'type' => $client->subscription_type,
            'is_active' => $client->is_active && !$client->isSubscriptionExpired(),
            'days_remaining' => $client->getDaysRemaining(),
            'ends_at' => $client->subscription_ends_at,
        ];

        // Top active users (by total messages sent)
        $topUsers = User::where('client_id', $client->id)
            ->approved()
            ->withCount(['smsLogs as sms_count' => function ($q) {
                $q->where('channel', 'sms');
            }, 'smsLogs as whatsapp_count' => function ($q) {
                $q->where('channel', 'whatsapp');
            }, 'callLogs as call_count'])
            ->orderByRaw('(sms_count + whatsapp_count + call_count) DESC')
            ->limit(5)
            ->get();

        return view('client.dashboard.index', compact(
            'clientAdmin',
            'client',
            'stats',
            'recentUsers',
            'recentMessages',
            'chartData',
            'subscriptionInfo',
            'topUsers'
        ));
    }

    /**
     * Get chart data for last 7 days.
     */
    protected function getChartDataLast7Days($userIds): array
    {
        $dates = [];
        $smsData = [];
        $whatsappData = [];
        $callData = [];

        for ($i = 6; $i >= 0; $i--) {
            $date = Carbon::now()->subDays($i)->format('Y-m-d');
            $dates[] = Carbon::now()->subDays($i)->format('M d');

            $smsData[] = SmsLog::whereIn('user_id', $userIds)
                ->smsChannel()
                ->whereDate('sent_at', $date)
                ->count();

            $whatsappData[] = SmsLog::whereIn('user_id', $userIds)
                ->whatsappChannel()
                ->whereDate('sent_at', $date)
                ->count();

            $callData[] = CallLog::whereIn('user_id', $userIds)
                ->whereDate('call_time', $date)
                ->count();
        }

        return [
            'labels' => $dates,
            'sms' => $smsData,
            'whatsapp' => $whatsappData,
            'calls' => $callData,
        ];
    }

    // ============ USER MANAGEMENT ============

    /**
     * List users for this client.
     */
    public function users(Request $request)
    {
        $client = $this->getCurrentClient();

        $query = User::where('client_id', $client->id)
            ->with(['createdByClientAdmin', 'settings']);

        // Filter by status
        if ($request->filled('status')) {
            $query->where('approval_status', $request->status);
        }

        // Search
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $users = $query->orderBy('created_at', 'desc')->paginate(20);

        // Stats for the view
        $stats = [
            'pending' => User::where('client_id', $client->id)->pending()->count(),
            'approved' => User::where('client_id', $client->id)->approved()->count(),
            'rejected' => User::where('client_id', $client->id)->rejected()->count(),
        ];

        return view('client.users.index', compact('users', 'client', 'stats'));
    }

    /**
     * Show create user form.
     */
    public function createUser()
    {
        $client = $this->getCurrentClient();

        // Check if client can add more users
        if (!$client->canAddMoreUsers()) {
            return back()->with('error', "User limit reached. Your plan allows maximum {$client->max_users} users.");
        }

        return view('client.users.create');
    }

    /**
     * Store new user.
     */
    public function storeUser(Request $request)
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();

        // Check limit
        if (!$client->canAddMoreUsers()) {
            return back()->with('error', "User limit reached. Your plan allows maximum {$client->max_users} users.");
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'required|string|max:20|unique:users,phone',
            'email' => 'nullable|email|unique:users,email',
            'password' => 'required|string|min:6',
        ]);

        $user = User::create([
            'name' => $validated['name'],
            'phone' => $validated['phone'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'client_id' => $client->id,
            'created_by_client_admin' => $clientAdmin->id,
            'approval_status' => 'pending', // Requires SuperAdmin approval
            'is_active' => true,
            'sms_service_enabled' => true,
        ]);

        return redirect()->route('client.users')
            ->with('success', "User '{$user->name}' created successfully. Waiting for SuperAdmin approval.");
    }

    /**
     * Show user details.
     */
    public function userDetails($id)
    {
        $client = $this->getCurrentClient();
        $user = User::where('client_id', $client->id)->with('settings')->findOrFail($id);

        // Get user stats
        $smsDays = (int) $user->smsLogs()->selectRaw('COUNT(DISTINCT DATE(created_at)) as cnt')->value('cnt');
        $callDays = (int) $user->callLogs()->selectRaw('COUNT(DISTINCT DATE(created_at)) as cnt')->value('cnt');
        $activeDays = $smsDays + $callDays;

        $stats = [
            'total_calls' => $user->callLogs()->count(),
            'total_sms' => $user->smsLogs()->smsChannel()->count(),
            'total_whatsapp' => $user->smsLogs()->whatsappChannel()->count(),
            'active_days' => $activeDays,
        ];

        // Recent SMS
        $recentSms = $user->smsLogs()
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        // Recent Calls
        $recentCalls = $user->callLogs()
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get();

        return view('client.users.details', compact('user', 'stats', 'recentSms', 'recentCalls'));
    }

    /**
     * Show edit user form.
     */
    public function editUser($id)
    {
        $client = $this->getCurrentClient();
        $user = User::where('client_id', $client->id)->findOrFail($id);

        return view('client.users.edit', compact('user'));
    }

    /**
     * Update user.
     */
    public function updateUser(Request $request, $id)
    {
        $client = $this->getCurrentClient();
        $user = User::where('client_id', $client->id)->findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|email|unique:users,email,' . $user->id,
            'phone' => 'required|string|max:20|unique:users,phone,' . $user->id,
            'password' => 'nullable|string|min:6',
            'is_active' => 'nullable',
            'sms_service_enabled' => 'nullable',
        ]);

        $updateData = [
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'],
            'is_active' => $request->has('is_active'),
            'sms_service_enabled' => $request->has('sms_service_enabled'),
        ];

        if (!empty($validated['password'])) {
            $updateData['password'] = Hash::make($validated['password']);
        }

        $user->update($updateData);

        return redirect()->route('client.users')
            ->with('success', "User '{$user->name}' updated successfully.");
    }

    /**
     * Toggle user active status.
     */
    public function toggleUserStatus($id)
    {
        $client = $this->getCurrentClient();
        $user = User::where('client_id', $client->id)->findOrFail($id);

        $user->update(['is_active' => !$user->is_active]);

        $status = $user->is_active ? 'activated' : 'deactivated';
        return back()->with('success', "User {$status} successfully.");
    }

    /**
     * Toggle SMS service for user.
     */
    public function toggleSmsService($id)
    {
        $client = $this->getCurrentClient();
        $user = User::where('client_id', $client->id)->findOrFail($id);

        $user->update(['sms_service_enabled' => !$user->sms_service_enabled]);

        $status = $user->sms_service_enabled ? 'enabled' : 'disabled';
        return back()->with('success', "SMS service {$status} for user.");
    }

    /**
     * Toggle WhatsApp service for user.
     */
    public function toggleWhatsAppService($id)
    {
        $client = $this->getCurrentClient();
        $user = User::where('client_id', $client->id)->findOrFail($id);

        $settings = $user->settings ?? UserSetting::create(['user_id' => $user->id]);
        $settings->update(['whatsapp_enabled' => !$settings->whatsapp_enabled]);

        $status = $settings->whatsapp_enabled ? 'enabled' : 'disabled';
        return back()->with('success', "WhatsApp service {$status} for user.");
    }

    /**
     * Reset user password.
     */
    public function resetUserPassword($id)
    {
        $client = $this->getCurrentClient();
        $user = User::where('client_id', $client->id)->findOrFail($id);

        $newPassword = Str::random(8);
        $user->update(['password' => Hash::make($newPassword)]);

        // Force logout after password reset
        $user->forceLogout('password_reset');

        return back()->with('success', "Password reset. New password: {$newPassword}");
    }

    /**
     * Force logout a user from their active device.
     */
    public function forceLogoutUser($id)
    {
        $client = $this->getCurrentClient();
        $user = User::where('client_id', $client->id)->findOrFail($id);

        $user->forceLogout('admin_force_logout');
        SessionLog::logForceLogout($user, 'Forced by client admin: ' . auth()->guard('client_admin')->user()->name);

        return back()->with('success', "User '{$user->name}' has been force logged out.");
    }

    // ============ TEMPLATE MANAGEMENT ============

    /**
     * List templates for this client.
     */
    public function templates(Request $request)
    {
        $client = $this->getCurrentClient();

        $query = MessageTemplate::where('client_id', $client->id);

        // Filter by type
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        // Filter by channel
        if ($request->filled('channel')) {
            $query->where('channel', $request->channel);
        }

        $templates = $query->orderBy('priority')->orderBy('name')->paginate(20);

        return view('client.templates.index', compact('templates'));
    }

    /**
     * Show edit template form.
     */
    public function editTemplate($id)
    {
        $client = $this->getCurrentClient();
        $template = MessageTemplate::where('client_id', $client->id)->findOrFail($id);

        return view('client.templates.edit', compact('template'));
    }

    /**
     * Update template.
     */
    public function updateTemplate(Request $request, $id)
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();
        $template = MessageTemplate::where('client_id', $client->id)->findOrFail($id);

        // Client can only edit content and is_active
        // name, type, call_type, channel are managed by SuperAdmin
        $validated = $request->validate([
            'content' => 'required|string',
        ]);

        $template->update([
            'content' => $validated['content'],
            'is_active' => $request->boolean('is_active'),
        ]);

        $template->recordModificationByClientAdmin($clientAdmin);

        return redirect()->route('client.templates')
            ->with('success', 'Template updated successfully.');
    }

    /**
     * Toggle template active status.
     */
    public function toggleTemplateStatus($id)
    {
        $client = $this->getCurrentClient();
        $template = MessageTemplate::where('client_id', $client->id)->findOrFail($id);

        $template->update(['is_active' => !$template->is_active]);

        $status = $template->is_active ? 'activated' : 'deactivated';
        return back()->with('success', "Template {$status} successfully.");
    }

    // ============ REPORTS ============

    /**
     * Show SMS logs.
     */
    public function smsLogs(Request $request)
    {
        $client = $this->getCurrentClient();
        $userIds = User::where('client_id', $client->id)->pluck('id');

        // Stats for the view — with channel breakdown
        $stats = [
            'total' => SmsLog::whereIn('user_id', $userIds)->count(),
            'sent' => SmsLog::whereIn('user_id', $userIds)->where('status', 'sent')->count(),
            'pending' => SmsLog::whereIn('user_id', $userIds)->where('status', 'pending')->count(),
            'failed' => SmsLog::whereIn('user_id', $userIds)->where('status', 'failed')->count(),
            'sms_total' => SmsLog::whereIn('user_id', $userIds)->smsChannel()->count(),
            'whatsapp_total' => SmsLog::whereIn('user_id', $userIds)->whatsappChannel()->count(),
        ];

        // Users for filter dropdown
        $users = User::where('client_id', $client->id)->orderBy('name')->get();

        $query = SmsLog::whereIn('user_id', $userIds)->with('user');

        // Filter by user
        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        // Search by phone number
        if ($request->filled('search')) {
            $query->where('phone_number', 'like', '%' . $request->search . '%');
        }

        // Filter by channel
        if ($request->filled('channel')) {
            $query->where('channel', $request->channel);
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        // Filter by date range
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $smsLogs = $query->orderBy('created_at', 'desc')->paginate(50);

        return view('client.reports.sms-logs', compact('smsLogs', 'stats', 'users'));
    }

    /**
     * Show call logs.
     */
    public function callLogs(Request $request)
    {
        $client = $this->getCurrentClient();
        $userIds = User::where('client_id', $client->id)->pluck('id');
        $statusOptions = CallLog::statusOptions();

        // Stats for the view
        $stats = [
            'total' => CallLog::whereIn('user_id', $userIds)->count(),
            'incoming' => CallLog::whereIn('user_id', $userIds)->where('call_type', 'incoming')->count(),
            'outgoing' => CallLog::whereIn('user_id', $userIds)->where('call_type', 'outgoing')->count(),
            'missed' => CallLog::whereIn('user_id', $userIds)->where('call_type', 'missed')->count(),
        ];

        // Users for filter dropdown
        $users = User::where('client_id', $client->id)->orderBy('name')->get();

        $query = CallLog::whereIn('user_id', $userIds)->with('user');

        // Filter by user
        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        // Search by phone number
        if ($request->filled('search')) {
            $query->where('phone_number', 'like', '%' . $request->search . '%');
        }

        // Filter by type
        if ($request->filled('type')) {
            $query->where('call_type', $request->type);
        }

        if ($request->filled('status_key')) {
            $query->where('status_key', $request->status_key);
        }

        if ($request->boolean('has_note')) {
            $query->whereNotNull('status_note')->where('status_note', '!=', '');
        }

        // Filter by date range
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $callLogs = $query->orderBy('created_at', 'desc')->paginate(50);

        return view('client.reports.call-logs', compact('callLogs', 'stats', 'users', 'statusOptions'));
    }

    // ============ PROFILE ============

    /**
     * Show profile page.
     */
    public function profile()
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();

        return view('client.profile.index', [
            'admin' => $clientAdmin,
            'clientAdmin' => $clientAdmin,
            'client' => $client,
        ]);
    }

    /**
     * Update profile.
     */
    public function updateProfile(Request $request)
    {
        $clientAdmin = $this->getCurrentClientAdmin();

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:client_admins,email,' . $clientAdmin->id,
            'phone' => 'nullable|string|max:20',
        ]);

        $clientAdmin->update($validated);

        return back()->with('success', 'Profile updated successfully.');
    }

    /**
     * Change password.
     */
    public function changePassword(Request $request)
    {
        $clientAdmin = $this->getCurrentClientAdmin();

        $validated = $request->validate([
            'current_password' => 'required',
            'password' => 'required|string|min:6|confirmed',
        ]);

        if (!Hash::check($validated['current_password'], $clientAdmin->password)) {
            return back()->withErrors(['current_password' => 'Current password is incorrect.']);
        }

        $clientAdmin->update(['password' => Hash::make($validated['password'])]);

        return back()->with('success', 'Password changed successfully.');
    }

    // ============ CLIENT ADMIN MANAGEMENT (Owner Only) ============

    /**
     * List client admins.
     */
    public function clientAdmins()
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();

        $admins = ClientAdmin::where('client_id', $client->id)
            ->orderBy('role')
            ->orderBy('name')
            ->get();

        return view('client.admins.index', compact('admins', 'client'));
    }

    /**
     * Show create client admin form.
     */
    public function createClientAdmin()
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();

        if (!$client->canAddMoreClientAdmins()) {
            return back()->with('error', "Admin limit reached. Your plan allows maximum {$client->max_client_admins} admins.");
        }

        return view('client.admins.create');
    }

    /**
     * Store new client admin.
     */
    public function storeClientAdmin(Request $request)
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();

        if (!$client->canAddMoreClientAdmins()) {
            return back()->with('error', "Admin limit reached. Your plan allows maximum {$client->max_client_admins} admins.");
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:client_admins,email',
            'phone' => 'nullable|string|max:20',
            'password' => 'required|string|min:6',
            'role' => 'required|in:owner,manager',
        ]);

        ClientAdmin::create([
            'client_id' => $client->id,
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'],
            'password' => Hash::make($validated['password']),
            'role' => $validated['role'],
            'is_active' => true,
        ]);

        return redirect()->route('client.admins')
            ->with('success', 'Client admin created successfully.');
    }

    /**
     * Toggle client admin status.
     */
    public function toggleClientAdminStatus($id)
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();

        $admin = ClientAdmin::where('client_id', $client->id)->findOrFail($id);

        // Cannot disable yourself
        if ($admin->id === $clientAdmin->id) {
            return back()->with('error', 'You cannot disable your own account.');
        }

        $admin->update(['is_active' => !$admin->is_active]);

        $status = $admin->is_active ? 'activated' : 'deactivated';
        return back()->with('success', "Admin {$status} successfully.");
    }

    /**
     * Show client admin permissions management page (from client panel).
     */
    public function clientAdminPermissions($id)
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();

        $adminToEdit = ClientAdmin::where('client_id', $client->id)->with('permissionOverrides')->findOrFail($id);

        // Cannot edit own permissions
        if ($adminToEdit->id === $clientAdmin->id) {
            return back()->with('error', 'You cannot edit your own permissions.');
        }

        $allPermissions = \App\Models\Permission::where('scope', 'client')
            ->get()
            ->groupBy('group');

        $roleKey = $adminToEdit->role === ClientAdmin::ROLE_OWNER
            ? \App\Models\RolePermission::ROLE_CLIENT_OWNER
            : \App\Models\RolePermission::ROLE_CLIENT_MANAGER;

        $rolePermissions = \App\Models\RolePermission::where('role', $roleKey)
            ->pluck('is_allowed', 'permission_key')
            ->toArray();

        return view('client.admins.permissions', compact(
            'client',
            'adminToEdit',
            'allPermissions',
            'rolePermissions'
        ));
    }

    /**
     * Update client admin permissions (from client panel).
     */
    public function updateClientAdminPermissions(Request $request, $id)
    {
        $clientAdmin = $this->getCurrentClientAdmin();
        $client = $this->getCurrentClient();

        $adminToEdit = ClientAdmin::where('client_id', $client->id)->findOrFail($id);

        // Cannot edit own permissions
        if ($adminToEdit->id === $clientAdmin->id) {
            return back()->with('error', 'You cannot edit your own permissions.');
        }

        // Clear existing overrides
        $adminToEdit->permissionOverrides()->delete();

        // Set new overrides
        $permissions = $request->input('permissions', []);
        foreach ($permissions as $key => $value) {
            if ($value !== '' && $value !== null) {
                \App\Models\ClientAdminPermission::create([
                    'client_admin_id' => $adminToEdit->id,
                    'permission_key' => $key,
                    'is_allowed' => (bool) $value,
                ]);
            }
        }

        return redirect()->route('client.admins')
            ->with('success', "Permissions updated for {$adminToEdit->name}");
    }

    // ============ EXPORT METHODS ============

    /**
     * Export SMS Logs to Excel.
     */
    public function exportSmsLogs(Request $request)
    {
        $client = $this->getCurrentClient();
        $userIds = User::where('client_id', $client->id)->pluck('id');

        $query = SmsLog::whereIn('user_id', $userIds)->with('user:id,name');

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }
        if ($request->filled('search')) {
            $query->where('phone_number', 'like', '%' . $request->search . '%');
        }
        if ($request->filled('channel')) {
            $query->where('channel', $request->channel);
        }
        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $data = $query->orderBy('created_at', 'desc')->get();

        $exportData = $data->map(function ($log) {
            return [
                'ID' => $log->id,
                'User' => $log->user->name ?? 'N/A',
                'Phone Number' => $log->phone_number,
                'Contact Name' => $log->contact_name ?? '',
                'Channel' => strtoupper($log->channel ?? 'sms'),
                'Message Type' => ucfirst(str_replace('_', ' ', $log->sms_type ?? 'unknown')),
                'Status' => strtoupper($log->status),
                'Message' => $log->message ?? '',
                'Sent At' => $log->sent_at ?? $log->created_at->format('Y-m-d H:i:s'),
            ];
        })->toArray();

        $dateRange = '';
        if ($request->filled('date_from') || $request->filled('date_to')) {
            $dateRange = 'Period: ' . ($request->date_from ?? 'Start') . ' to ' . ($request->date_to ?? 'Now');
        }

        $filename = 'sms_logs_' . $client->company_name . '_' . now()->format('Y-m-d_His');

        return $this->excelExportService->export(
            $exportData,
            $filename,
            'SMS Logs - ' . $client->company_name,
            $dateRange
        );
    }

    /**
     * Export Call Logs to Excel.
     */
    public function exportCallLogs(Request $request)
    {
        $client = $this->getCurrentClient();
        $userIds = User::where('client_id', $client->id)->pluck('id');

        $query = CallLog::whereIn('user_id', $userIds)->with('user:id,name');

        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }
        if ($request->filled('search')) {
            $query->where('phone_number', 'like', '%' . $request->search . '%');
        }
        if ($request->filled('type')) {
            $query->where('call_type', $request->type);
        }
        if ($request->filled('status_key')) {
            $query->where('status_key', $request->status_key);
        }
        if ($request->boolean('has_note')) {
            $query->whereNotNull('status_note')->where('status_note', '!=', '');
        }
        if ($request->filled('date_from')) {
            $query->whereDate('created_at', '>=', $request->date_from);
        }
        if ($request->filled('date_to')) {
            $query->whereDate('created_at', '<=', $request->date_to);
        }

        $data = $query->orderBy('created_at', 'desc')->get();

        $exportData = $data->map(function ($log) {
            return [
                'ID' => $log->id,
                'User' => $log->user->name ?? 'N/A',
                'Phone Number' => $log->phone_number,
                'Contact Name' => $log->contact_name ?? '',
                'Call Type' => strtoupper($log->call_type),
                'Status' => $log->status_label ?? '',
                'Status Note' => $log->status_note ?? '',
                'Duration' => $log->call_duration ? gmdate('H:i:s', $log->call_duration) : '00:00:00',
                'Duration (sec)' => $log->call_duration ?? 0,
                'Auto-Reply Sent' => $log->sms_sent ? 'Yes' : 'No',
                'Time' => optional($log->call_time)->format('Y-m-d H:i:s') ?? $log->created_at->format('Y-m-d H:i:s'),
            ];
        })->toArray();

        $dateRange = '';
        if ($request->filled('date_from') || $request->filled('date_to')) {
            $dateRange = 'Period: ' . ($request->date_from ?? 'Start') . ' to ' . ($request->date_to ?? 'Now');
        }

        $filename = 'call_logs_' . $client->company_name . '_' . now()->format('Y-m-d_His');

        return $this->excelExportService->export(
            $exportData,
            $filename,
            'Call Logs - ' . $client->company_name,
            $dateRange
        );
    }
}
