<?php

namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Core\Security;
use App\Models\User;
use App\Models\WhatsAppSession;
use App\Core\Database;

class StaffController extends BaseController
{
    /**
     * List all staff agents for the merchant company
     * GET /api/staff
     */
    public function index(Request $request, Response $response): void
    {
        $companyId = $request->company_id;

        // Fetch users belonging to this company who are 'staff'
        $staff = Database::select(
            "SELECT u.id, u.name, u.email, u.role, u.status, u.whatsapp_session_id, w.name as session_name, w.phone as session_phone 
             FROM users u 
             LEFT JOIN whatsapp_sessions w ON u.whatsapp_session_id = w.id
             WHERE u.company_id = ? AND u.role = 'staff'
             ORDER BY u.id DESC",
            [$companyId]
        );

        foreach ($staff as &$member) {
            $member['email'] = Security::decrypt($member['email']);
            if (!empty($member['session_phone'])) {
                $member['session_phone'] = Security::decrypt($member['session_phone']);
            }
        }

        $response->json([
            'status' => 'success',
            'data' => $staff
        ]);
    }

    /**
     * Create a new customer service agent (staff)
     * POST /api/staff
     */
    public function store(Request $request, Response $response): void
    {
        $companyId = $request->company_id;
        $errors = $this->validate($request, [
            'name'     => 'required|min:3',
            'email'    => 'required|email',
            'password' => 'required|min:6'
        ]);

        if (!empty($errors)) {
            $response->json(['errors' => $errors], 400);
            return;
        }

        // Fetch subscription limits for agents
        $activeSub = \App\Models\CompanySubscription::findActiveByCompany($companyId);
        $maxAgents = 1;
        if (isset($request->is_super_admin) && $request->is_super_admin) {
            $maxAgents = 999;
        } elseif ($activeSub) {
            $maxAgents = (int)($activeSub['max_agents'] ?? 1);
        }

        $currentStaffCount = Database::selectOne("SELECT COUNT(*) as count FROM users WHERE company_id = ? AND role = 'staff'", [$companyId])['count'] ?? 0;
        if ($currentStaffCount >= $maxAgents) {
            $response->status(400)->json([
                'status' => 'error',
                'error' => "You have reached the maximum number of staff agents allowed by your plan ({$maxAgents})."
            ]);
            return;
        }

        $body = $request->getBody();
        $email = strtolower(trim($body['email']));

        // Check if user already exists
        $existing = User::findByEmail($email);
        if ($existing) {
            $response->json(['errors' => ['email' => ['This email is already registered.']]], 409);
            return;
        }

        // Validate session if assigned
        $whatsappSessionId = isset($body['whatsapp_session_id']) && $body['whatsapp_session_id'] !== '' ? (int)$body['whatsapp_session_id'] : null;
        if ($whatsappSessionId) {
            $session = WhatsAppSession::findSecure($whatsappSessionId);
            if (!$session || (int)$session['company_id'] !== (int)$companyId) {
                $response->status(400)->json(['error' => 'Invalid WhatsApp session assigned']);
                return;
            }
        }

        try {
            $userId = User::createSecure([
                'company_id' => $companyId,
                'name' => trim($body['name']),
                'email' => $email,
                'password' => $body['password'],
                'role' => 'staff',
                'status' => 'active',
                'whatsapp_session_id' => $whatsappSessionId
            ]);

            $response->json([
                'status' => 'success',
                'message' => 'Agent created successfully',
                'data' => [
                    'id' => $userId,
                    'name' => trim($body['name']),
                    'email' => $email,
                    'role' => 'staff',
                    'whatsapp_session_id' => $whatsappSessionId
                ]
            ], 201);
        } catch (\Exception $e) {
            error_log("[Staff Controller Error] " . $e->getMessage());
            $response->status(500)->json(['error' => 'Failed to create agent: ' . $e->getMessage()]);
        }
    }

    /**
     * Delete an agent
     * DELETE /api/staff
     */
    public function delete(Request $request, Response $response): void
    {
        $companyId = $request->company_id;
        $body = $request->getBody();
        $agentId = $body['agent_id'] ?? null;

        if (!$agentId) {
            $response->status(400)->json(['error' => 'Missing agent_id']);
            return;
        }

        $user = User::find($agentId);
        if (!$user || (int)$user['company_id'] !== (int)$companyId || $user['role'] !== 'staff') {
            $response->status(404)->json(['error' => 'Agent not found']);
            return;
        }

        User::delete((int)$agentId);

        $response->json([
            'status' => 'success',
            'message' => 'Agent deleted successfully'
        ]);
    }

    /**
     * Assign a specific WhatsApp session to an agent
     * PUT /api/staff/assign
     */
    public function assignSession(Request $request, Response $response): void
    {
        $companyId = $request->company_id;
        $body = $request->getBody();
        
        $agentId = $body['agent_id'] ?? null;
        $whatsappSessionId = isset($body['whatsapp_session_id']) && $body['whatsapp_session_id'] !== '' ? (int)$body['whatsapp_session_id'] : null;

        if (!$agentId) {
            $response->status(400)->json(['error' => 'Missing agent_id']);
            return;
        }

        $user = User::find($agentId);
        if (!$user || (int)$user['company_id'] !== (int)$companyId || $user['role'] !== 'staff') {
            $response->status(404)->json(['error' => 'Agent not found']);
            return;
        }

        if ($whatsappSessionId) {
            $session = WhatsAppSession::findSecure($whatsappSessionId);
            if (!$session || (int)$session['company_id'] !== (int)$companyId) {
                $response->status(400)->json(['error' => 'Invalid WhatsApp session']);
                return;
            }
        }

        try {
            User::update((int)$agentId, [
                'whatsapp_session_id' => $whatsappSessionId
            ]);

            $response->json([
                'status' => 'success',
                'message' => 'WhatsApp session successfully assigned to agent'
            ]);
        } catch (\Exception $e) {
            $response->status(500)->json(['error' => 'Failed to assign session: ' . $e->getMessage()]);
        }
    }
}
