<?php
require_once 'config/database.php';
require_once 'controllers/InvoicesController.php'; // For assignInvoices

class TeamManagementController {
    private $conn;
    private $invoicesController;

    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
        $this->invoicesController = new InvoicesController();
    }

    // LIST TEAM MEMBERS
    public function getTeamMembers($filters = [], $userId, $userRole) {
        $query = "SELECT 
            u.id, CONCAT(u.first_name, ' ', u.last_name) as name, u.email, u.phone, u.role_id, u.status, u.created_at,
            u.specialization, u.current_workload, u.max_workload,
            u.monthly_calls, u.monthly_closures, u.monthly_recovered,
            u.last_login
        FROM users u
        WHERE u.role_id = '3'";

        $params = [];

        if ($userRole === 2) { // Supervisor
            $query .= " AND u.supervisor_id = :user_id";
            $params[':user_id'] = $userId;
        }

        if (!empty($filters['search'])) {
            $search = "%" . $filters['search'] . "%";
            $query .= " AND (u.first_name LIKE :search OR u.email LIKE :search)";
            $params[':search'] = $search;
        }

        $stmt = $this->conn->prepare($query);
        $stmt->execute($params);
        $members = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($members as &$m) {
            $m['specialization'] = json_decode($m['specialization'] ?? '[]', true);
            $target = $this->getCurrentTarget($m['id']);
            $m['monthlyStats'] = [
                'callsCompleted' => (int)$m['monthly_calls'],
                'successfulClosures' => (int)$m['monthly_closures'],
                'amountRecovered' => (float)$m['monthly_recovered'],
                'targetAchievement' => $target > 0 ? round(($m['monthly_recovered'] / $target) * 100) : 0
            ];
            $m['performanceScore'] = $this->calculatePerformanceScore($m);
        }

        return json_encode([
            'status' => 'success',
            'data' => $members,
            'stats' => $this->getTeamStats($userId, $userRole)
        ]);
    }

    private function getCurrentTarget($ipoId) {
        $stmt = $this->conn->prepare("
            SELECT target FROM performance_target 
            WHERE ipo_id = :id AND period = 'monthly' 
            AND NOW() BETWEEN created_at AND DATE_ADD(created_at, INTERVAL 1 MONTH)
            ORDER BY created_at DESC LIMIT 1
        ");
        $stmt->bindParam(':id', $ipoId);
        $stmt->execute();
        return (float)($stmt->fetchColumn() ?? 0);
    }

    private function calculatePerformanceScore($member) {
        $calls = $member['monthly_calls'] ?? 0;
        $closures = $member['monthly_closures'] ?? 0;
        $recovered = $member['monthly_recovered'] ?? 0;
        $target = $this->getCurrentTarget($member['id']);
        $achievement = $target > 0 ? ($recovered / $target) * 100 : 0;
        return min(100, round(($calls * 0.3) + ($closures * 0.4) + ($achievement * 0.3)));
    }

    private function getTeamStats($userId, $userRole) {
        $query = "SELECT 
            COUNT(*) as activeMembers,
            SUM(monthly_calls) as totalCalls,
            SUM(monthly_recovered) as totalRecovered,
            AVG(performance_score) as avgPerformance,
            SUM(current_workload) as totalWorkload,
            SUM(max_workload) as maxWorkload
        FROM users 
        WHERE role_id = '3' AND status = 'active'";

        if ($userRole === 2) $query .= " AND supervisor_id = :user_id";

        $stmt = $this->conn->prepare($query);
        if ($userRole === 2) $stmt->bindParam(':user_id', $userId);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        $util = $row['maxWorkload'] > 0 ? ($row['totalWorkload'] / $row['maxWorkload']) * 100 : 0;

        return [
            'activeMembers' => (int)$row['activeMembers'],
            'totalCalls' => (int)$row['totalCalls'],
            'totalRecovered' => (float)$row['totalRecovered'],
            'avgPerformance' => round((float)$row['avgPerformance'] ?? 0),
            'workloadUtilization' => round($util)
        ];
    }

    // ASSIGN WORK (Uses your existing assignInvoices)
    public function assignWork($data, $userId, $userName) {
        if (empty($data['invoice_ids']) || empty($data['assigned_to'])) {
            return json_encode(['status' => 'error', 'message' => 'Missing invoice_ids or assigned_to']);
        }

        // Get assigned_to name
        $stmt = $this->conn->prepare("SELECT name FROM users WHERE id = :id");
        $stmt->bindParam(':id', $data['assigned_to']);
        $stmt->execute();
        $assignedName = $stmt->fetchColumn();
        if (!$assignedName) return json_encode(['status' => 'error', 'message' => 'Invalid assigned_to']);

        $data['assigned_to_name'] = $assignedName;

        // Use your existing method
        $result = json_decode($this->invoicesController->assignInvoices($data), true);
        if ($result['status'] !== 'success') return json_encode($result);

        // Update workload
        $this->updateWorkload($data['assigned_to'], +count($data['invoice_ids']));

        return json_encode(['status' => 'success', 'message' => 'Assigned and workload updated']);
    }

    private function updateWorkload($userId, $delta) {
        $stmt = $this->conn->prepare("
            UPDATE users 
            SET current_workload = GREATEST(0, LEAST(max_workload, current_workload + :delta))
            WHERE id = :id
        ");
        $stmt->bindParam(':delta', $delta, PDO::PARAM_INT);
        $stmt->bindParam(':id', $userId);
        $stmt->execute();
    }

    // LIST ASSIGNMENTS (from invoices + follow_ups)
    public function getAssignments($userId, $userRole) {
        $query = "SELECT 
            i.id, i.invoice_number as invoiceId, 
            CONCAT(i.first_name, ' ', i.last_name) as taxpayerName,
            i.amount, i.priority, CONCAT(u.first_name, ' ', u.last_name) as name, as assignedTo,
            i.updated_at as assignedDate, f.due_date as dueDate,
            f.status
        FROM invoices i
        LEFT JOIN users u ON i.assigned_to = u.id
        LEFT JOIN follow_ups f ON i.id = f.invoice_id AND f.ipo_id = i.assigned_to
        WHERE i.assigned_to IS NOT NULL ";

        if ($userRole === 2) {
            $query .= " AND i.assigned_to IN (SELECT id FROM users WHERE supervisor_id = :user_id)";
        } elseif ($userRole === 3) {
            $query .= " AND i.assigned_to = :user_id";
        }

        $query .= " ORDER BY f.due_date ASC";

        $stmt = $this->conn->prepare($query);
        if ($userRole !== 1) $stmt->bindParam(':user_id', $userId);
        $stmt->execute();
        $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);

        return json_encode(['status' => 'success', 'data' => $assignments]);
    }

    // SET TARGET (uses your performance_target table)
    public function setTarget($data, $userId, $userName) {
        $required = ['ipo_id', 'metric', 'target', 'unit', 'period'];
        foreach ($required as $f) {
            if (empty($data[$f])) return json_encode(['status' => 'error', 'message' => "Missing: $f"]);
        }

        try {
            $query = "INSERT INTO performance_target (
                metric, target, current, unit, period, ipo_id
            ) VALUES (
                :metric, :target, 0, :unit, :period, :ipo_id
            ) ON DUPLICATE KEY UPDATE 
                target = VALUES(target), current = 0, updated_at = NOW()";

            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':metric', $data['metric']);
            $stmt->bindParam(':target', $data['target']);
            $stmt->bindParam(':unit', $data['unit']);
            $stmt->bindParam(':period', $data['period']);
            $stmt->bindParam(':ipo_id', $data['ipo_id']);
            $stmt->execute();

            return json_encode(['status' => 'success']);
        } catch (Exception $e) {
            return json_encode(['status' => 'error', 'message' => 'Failed']);
        }
    }
}
?>