<?php

namespace App\Controllers;

use App\Services\Database;

class RequirementsController extends BaseController
{
    /**
     * Vista principal de requerimientos
     */
    public function index()
    {
        $this->requireAuth();
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handleAction();
            return;
        }

        $db = Database::getInstance();
        $user = $_SESSION['user'] ?? [];
        $userId = $user['id'] ?? 0;

        // Obtener filtros
        $status = $_GET['status'] ?? '';
        $type = $_GET['type'] ?? '';
        $search = $_GET['search'] ?? '';
        $page = max(1, intval($_GET['page'] ?? 1));
        $perPage = 20;
        $offset = ($page - 1) * $perPage;

        // Construir query con filtros
        $where = ['1=1'];
        $params = [];

        if ($status) {
            $where[] = 'r.status = ?';
            $params[] = $status;
        }

        if ($type) {
            $where[] = 'r.type = ?';
            $params[] = $type;
        }

        if ($search) {
            $where[] = '(r.title LIKE ? OR r.description LIKE ? OR r.code LIKE ?)';
            $searchTerm = "%$search%";
            $params[] = $searchTerm;
            $params[] = $searchTerm;
            $params[] = $searchTerm;
        }

        // Si no es admin, solo ver sus propios requerimientos
        if (!($user['is_admin'] ?? false)) {
            $where[] = 'r.requester_user_id = ?';
            $params[] = $userId;
        }

        $whereClause = implode(' AND ', $where);

        // Obtener total de registros
        $totalQuery = "SELECT COUNT(*) as total FROM requirements r WHERE $whereClause";
        $totalResult = $db->fetchOne($totalQuery, $params);
        $total = $totalResult['total'] ?? 0;
        $totalPages = ceil($total / $perPage);

        // Obtener requerimientos
        $query = "
            SELECT 
                r.*,
                CONCAT(u.first_name, ' ', u.last_name) as requester_name,
                CONCAT(a.first_name, ' ', a.last_name) as assigned_name,
                (SELECT COUNT(*) FROM requirement_comments WHERE requirement_id = r.id) as comments_count
            FROM requirements r
            LEFT JOIN users u ON r.requester_user_id = u.id
            LEFT JOIN users a ON r.assigned_user_id = a.id
            WHERE $whereClause
            ORDER BY r.created_at DESC
            LIMIT ? OFFSET ?
        ";
        
        $params[] = $perPage;
        $params[] = $offset;
        
        $requirements = $db->fetchAll($query, $params);

        // Estadísticas
        $stats = $this->getStats();

        $this->render('requirements/index', [
            'requirements' => $requirements,
            'stats' => $stats,
            'total' => $total,
            'page' => $page,
            'totalPages' => $totalPages,
            'filters' => [
                'status' => $status,
                'type' => $type,
                'search' => $search
            ]
        ]);
    }

    /**
     * Crear nuevo requerimiento
     */
    public function create()
    {
        $this->requireAuth();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->handleCreate();
            return;
        }

        $this->render('requirements/create', []);
    }

    /**
     * Ver detalle de un requerimiento
     */
    public function view($id)
    {
        $this->requireAuth();

        $db = Database::getInstance();
        $user = $_SESSION['user'] ?? [];

        $requirement = $db->fetchOne("
            SELECT 
                r.*,
                CONCAT(u.first_name, ' ', u.last_name) as requester_name,
                u.email as requester_email,
                CONCAT(a.first_name, ' ', a.last_name) as assigned_name
            FROM requirements r
            LEFT JOIN users u ON r.requester_user_id = u.id
            LEFT JOIN users a ON r.assigned_user_id = a.id
            WHERE r.id = ?
        ", [$id]);

        if (!$requirement) {
            header('Location: /requirements');
            exit;
        }

        // Verificar permisos
        if (!($user['is_admin'] ?? false) && $requirement['requester_user_id'] != ($user['id'] ?? 0)) {
            header('Location: /requirements');
            exit;
        }

        // Obtener comentarios
        $comments = $db->fetchAll("
            SELECT 
                c.*,
                CONCAT(u.first_name, ' ', u.last_name) as user_name
            FROM requirement_comments c
            LEFT JOIN users u ON c.user_id = u.id
            WHERE c.requirement_id = ?
            ORDER BY c.created_at ASC
        ", [$id]);

        // Obtener historial
        $history = $db->fetchAll("
            SELECT 
                h.*,
                CONCAT(u.first_name, ' ', u.last_name) as user_name
            FROM requirement_history h
            LEFT JOIN users u ON h.user_id = u.id
            WHERE h.requirement_id = ?
            ORDER BY h.created_at DESC
            LIMIT 50
        ", [$id]);

        // Obtener adjuntos
        $attachments = $db->fetchAll("
            SELECT a.*, a.file_name as file_original_name
            FROM requirement_attachments a
            WHERE a.requirement_id = ?
            ORDER BY a.created_at DESC
        ", [$id]);

        // Obtener todos los usuarios activos con sus equipos
        $allUsers = $db->fetchAll("
            SELECT u.id, CONCAT(u.first_name, ' ', u.last_name) as name, u.email, u.first_name, u.last_name
            FROM users u 
            WHERE u.is_active = 1 
            ORDER BY u.first_name, u.last_name
        ", []);
        
        // Obtener miembros de equipos con sus equipos asociados
        $teamMembers = $db->fetchAll("
            SELECT tm.user_id, t.code as team_code, u.first_name, u.last_name
            FROM team_members tm
            JOIN teams t ON tm.team_id = t.id
            JOIN users u ON tm.user_id = u.id
            WHERE t.is_active = 1
        ", []);
        
        // Crear un mapa de usuarios por equipo
        $usersByTeam = [];
        foreach ($teamMembers as $member) {
            if (!isset($usersByTeam[$member['team_code']])) {
                $usersByTeam[$member['team_code']] = [];
            }
            $usersByTeam[$member['team_code']][] = [
                'id' => $member['user_id'],
                'name' => $member['first_name'] . ' ' . $member['last_name']
            ];
        }

        // Determinar permisos
        $isAdmin = in_array($user['role_name'] ?? '', ['super_admin', 'admin']);
        $userRole = $user['role_name'] ?? 'user';
        $canEdit = $isAdmin || ($requirement['requester_user_id'] == ($user['id'] ?? 0));

        // Obtener items del backlog asociados al requerimiento con trazabilidad completa
        $backlogItems = $db->fetchAll("
            SELECT pbi.*, 
                   p.code as project_code, p.name as project_name,
                   s.name as sprint_name, s.id as sprint_id, s.status as sprint_status,
                   u.first_name as assigned_first_name, u.last_name as assigned_last_name,
                   (SELECT COUNT(*) FROM tasks WHERE backlog_item_id = pbi.id) as tasks_count,
                   (SELECT COUNT(*) FROM tasks WHERE backlog_item_id = pbi.id AND status = 'done') as tasks_completed
            FROM product_backlog_items pbi
            LEFT JOIN projects p ON pbi.project_id = p.id
            LEFT JOIN sprint_backlog sb ON pbi.id = sb.backlog_item_id
            LEFT JOIN sprints s ON sb.sprint_id = s.id
            LEFT JOIN users u ON pbi.assigned_to = u.id
            WHERE pbi.requirement_id = ?
            ORDER BY pbi.created_at DESC
        ", [$id]);

        $this->render('requirements/view', [
            'requirement' => $requirement,
            'comments' => $comments,
            'history' => $history,
            'attachments' => $attachments,
            'allUsers' => $allUsers,
            'usersByTeam' => $usersByTeam,
            'canEdit' => $canEdit,
            'isAdmin' => $isAdmin,
            'userRole' => $userRole,
            'backlogItems' => $backlogItems
        ]);
    }

    /**
     * Descargar archivo adjunto
     */
    public function download($id)
    {
        $this->requireAuth();

        $db = Database::getInstance();
        $attachment = $db->fetchOne("
            SELECT a.*, r.requester_user_id, a.mime_type as file_type, a.file_name as file_original_name
            FROM requirement_attachments a
            JOIN requirements r ON a.requirement_id = r.id
            WHERE a.id = ?
        ", [$id]);

        if (!$attachment) {
            header('Location: /requirements');
            exit;
        }

        // Verificar permisos
        $user = $_SESSION['user'] ?? [];
        if (!($user['is_admin'] ?? false) && $attachment['requester_user_id'] != ($user['id'] ?? 0)) {
            header('Location: /requirements');
            exit;
        }

        $filePath = $attachment['file_path'];

        if (!file_exists($filePath)) {
            header('Location: /requirements/view/' . $attachment['requirement_id'] . '?error=Archivo no encontrado');
            exit;
        }

        // Descargar archivo
        header('Content-Type: ' . $attachment['file_type']);
        header('Content-Disposition: attachment; filename="' . $attachment['file_original_name'] . '"');
        header('Content-Length: ' . filesize($filePath));
        readfile($filePath);
        exit;
    }

    /**
     * Manejar acciones POST
     */
    public function handleAction()
    {
        try {
            $action = $_POST['action'] ?? '';
            $csrfToken = $_POST['csrf_token'] ?? '';

            if (!$this->validateCsrfToken($csrfToken)) {
                throw new \Exception('Token CSRF inválido');
            }

            switch ($action) {
                case 'change_status':
                    $this->changeStatus();
                    break;
                case 'add_comment':
                    $this->addComment();
                    break;
                case 'assign':
                    $this->assignRequirement();
                    break;
                case 'reassign':
                    $this->reassignRequirement();
                    break;
                case 'classify':
                    $this->classifyRequirement();
                    break;
                default:
                    throw new \Exception('Acción no válida');
            }

        } catch (\Exception $e) {
            header('Location: /requirements?error=' . urlencode($e->getMessage()));
            exit;
        }
    }

    /**
     * Crear nuevo requerimiento
     */
    private function handleCreate()
    {
        header('Content-Type: application/json');
        
        try {
            $csrfToken = $_POST['csrf_token'] ?? '';
            if (!$this->validateCsrfToken($csrfToken)) {
                throw new \Exception('Token CSRF inválido');
            }

            $user = $_SESSION['user'] ?? [];
            $userId = $user['id'] ?? 0;

            if ($userId === 0) {
                throw new \Exception('Usuario no autenticado');
            }

            $title = trim($_POST['title'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $type = $_POST['type'] ?? '';
            $priority = $_POST['priority'] ?? 'medium';
            $department = trim($_POST['department'] ?? '');
            $affectedUsers = intval($_POST['affected_users'] ?? 0);
            $expectedImpact = trim($_POST['expected_impact'] ?? '');

            if (empty($title) || empty($description) || empty($type)) {
                throw new \Exception('Título, descripción y tipo son requeridos');
            }

            // Generar código único
            $code = $this->generateRequirementCode();

            // Auto-clasificar y asignar equipo según tipo
            list($team, $slaHours) = $this->autoClassify($type);

            // Calcular fecha de vencimiento
            $dueDate = date('Y-m-d H:i:s', strtotime("+$slaHours hours"));

            $db = Database::getInstance();
            
            $requirementId = $db->insert("
                INSERT INTO requirements (
                    code, title, description, type, priority, status,
                    requester_user_id, department, affected_users, expected_impact,
                    assigned_team, sla_hours, due_date
                ) VALUES (?, ?, ?, ?, ?, 'new', ?, ?, ?, ?, ?, ?, ?)
            ", [
                $code, $title, $description, $type, $priority,
                $userId, $department, $affectedUsers, $expectedImpact,
                $team, $slaHours, $dueDate
            ]);

            // Registrar en historial
            $this->logHistory($requirementId, $userId, 'created', null, null, null);

            // Procesar archivos adjuntos si existen
            if (isset($_FILES['attachments']) && !empty($_FILES['attachments']['name'][0])) {
                $this->processAttachments($requirementId, $userId);
            }

            // Redirigir al detalle del requerimiento creado
            header('Location: /requirements/view/' . $requirementId . '?success=Requerimiento ' . $code . ' creado correctamente');
            exit;

        } catch (\Exception $e) {
            error_log("Error creating requirement: " . $e->getMessage());
            error_log("Stack trace: " . $e->getTraceAsString());
            header('Location: /requirements/create?error=' . urlencode($e->getMessage()));
            exit;
        }
    }

    /**
     * Procesar archivos adjuntos
     */
    private function processAttachments($requirementId, $userId)
    {
        $uploadDir = __DIR__ . '/../../uploads/requirements/';
        
        // Crear directorio si no existe
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        $db = Database::getInstance();
        $files = $_FILES['attachments'];
        $totalFiles = count($files['name']);

        for ($i = 0; $i < $totalFiles; $i++) {
            if ($files['error'][$i] === UPLOAD_ERR_OK) {
                $originalName = basename($files['name'][$i]);
                $tmpName = $files['tmp_name'][$i];
                $fileSize = $files['size'][$i];
                $fileType = $files['type'][$i];

                // Validar tamaño (máximo 10MB)
                if ($fileSize > 10 * 1024 * 1024) {
                    throw new \Exception("El archivo $originalName excede el tamaño máximo de 10MB");
                }

                // Generar nombre único para evitar colisiones
                $extension = pathinfo($originalName, PATHINFO_EXTENSION);
                $fileName = uniqid('req_' . $requirementId . '_') . '.' . $extension;
                $filePath = $uploadDir . $fileName;

                // Mover archivo
                if (move_uploaded_file($tmpName, $filePath)) {
                    // Guardar en base de datos
                    $db->insert("
                        INSERT INTO requirement_attachments 
                        (requirement_id, uploaded_by, file_name, file_path, file_size, mime_type)
                        VALUES (?, ?, ?, ?, ?, ?)
                    ", [$requirementId, $userId, $originalName, $filePath, $fileSize, $fileType]);
                } else {
                    throw new \Exception("Error al subir el archivo $originalName");
                }
            }
        }
    }

    /**
     * Cambiar estado de requerimiento
     */
    private function changeStatus()
    {
        $requirementId = $_POST['requirement_id'] ?? '';
        $newStatus = $_POST['status'] ?? '';

        error_log("changeStatus called: req_id=$requirementId, status=$newStatus");

        if (empty($requirementId) || empty($newStatus)) {
            throw new \Exception('ID y estado son requeridos');
        }

        $user = $_SESSION['user'] ?? [];
        $userId = $user['id'] ?? 0;

        $db = Database::getInstance();
        $requirement = $db->fetchOne("SELECT * FROM requirements WHERE id = ?", [$requirementId]);

        if (!$requirement) {
            throw new \Exception('Requerimiento no encontrado');
        }

        $oldStatus = $requirement['status'];
        
        // Actualizar estado
        $db->query("UPDATE requirements SET status = ?, updated_at = NOW() WHERE id = ?", [$newStatus, $requirementId]);

        // Registrar en historial
        $this->logHistory($requirementId, $userId, 'status_changed', 'status', $oldStatus, $newStatus);

        // Si el requerimiento está asignado a un proyecto, recalcular progreso
        if (!empty($requirement['project_id'])) {
            $this->updateProjectProgress($requirement['project_id']);
        }

        // Redirigir de vuelta a la vista del requerimiento
        header('Location: /requirements/view/' . $requirementId . '?success=Estado actualizado correctamente');
        exit;
    }

    /**
     * Agregar comentario
     */
    private function addComment()
    {
        $requirementId = $_POST['requirement_id'] ?? '';
        $comment = trim($_POST['comment'] ?? '');
        $isInternal = !empty($_POST['is_internal']);

        if (empty($requirementId) || empty($comment)) {
            throw new \Exception('Requerimiento y comentario son requeridos');
        }

        $user = $_SESSION['user'] ?? [];
        $userId = $user['id'] ?? 0;

        $db = Database::getInstance();
        $db->insert("
            INSERT INTO requirement_comments (requirement_id, user_id, comment, is_internal)
            VALUES (?, ?, ?, ?)
        ", [$requirementId, $userId, $comment, $isInternal ? 1 : 0]);

        // Registrar en historial
        $this->logHistory($requirementId, $userId, 'comment_added', null, null, null);

        // Redirigir de vuelta a la vista del requerimiento
        header('Location: /requirements/view/' . $requirementId . '?success=Comentario agregado correctamente');
        exit;
    }

    /**
     * Asignar requerimiento
     */
    private function assignRequirement()
    {
        $requirementId = $_POST['requirement_id'] ?? '';
        $assignedUserId = $_POST['assigned_user_id'] ?? null;

        if (empty($requirementId)) {
            throw new \Exception('ID de requerimiento requerido');
        }

        $user = $_SESSION['user'] ?? [];
        $userId = $user['id'] ?? 0;

        $db = Database::getInstance();
        $db->update("
            UPDATE requirements 
            SET assigned_user_id = ?, updated_at = NOW() 
            WHERE id = ?
        ", [$assignedUserId ?: null, $requirementId]);

        $this->logHistory($requirementId, $userId, 'assigned', 'assigned_user_id', null, $assignedUserId);

        echo json_encode(['success' => true, 'message' => 'Asignación actualizada']);
    }

    /**
     * Clasificar requerimiento
     */
    private function classifyRequirement()
    {
        $requirementId = $_POST['requirement_id'] ?? '';
        $type = $_POST['type'] ?? '';

        if (empty($requirementId) || empty($type)) {
            throw new \Exception('ID y tipo son requeridos');
        }

        list($team, $slaHours) = $this->autoClassify($type);
        $dueDate = date('Y-m-d H:i:s', strtotime("+$slaHours hours"));

        $user = $_SESSION['user'] ?? [];
        $userId = $user['id'] ?? 0;

        $db = Database::getInstance();
        $db->update("
            UPDATE requirements 
            SET type = ?, assigned_team = ?, sla_hours = ?, due_date = ?, status = 'classified', updated_at = NOW()
            WHERE id = ?
        ", [$type, $team, $slaHours, $dueDate, $requirementId]);

        $this->logHistory($requirementId, $userId, 'classified', 'type', null, $type);

        echo json_encode([
            'success' => true,
            'message' => "Clasificado como $type - Equipo: $team - SLA: $slaHours hrs"
        ]);
    }

    /**
     * Reasignar requerimiento (cambiar tipo, equipo y/o usuario)
     */
    private function reassignRequirement()
    {
        $requirementId = $_POST['requirement_id'] ?? '';
        $type = $_POST['type'] ?? '';
        $team = $_POST['team'] ?? '';
        $assignedUserId = $_POST['assigned_user_id'] ?? '';
        $reason = $_POST['reason'] ?? '';
        error_log("reassignRequirement called: req_id=$requirementId, type=$type, team=$team");
        if (empty($requirementId) || empty($type) || empty($team) || empty($reason)) {
            throw new \Exception('Todos los campos son requeridos excepto el usuario asignado');
        }

        $user = $_SESSION['user'] ?? [];
        $userId = $user['id'] ?? 0;

        // Obtener datos actuales del requerimiento
        $db = Database::getInstance();
        $current = $db->fetchOne("SELECT type, assigned_team, assigned_user_id FROM requirements WHERE id = ?", [$requirementId]);

        if (!$current) {
            throw new \Exception('Requerimiento no encontrado');
        }

        // Calcular nuevo SLA según el tipo
        list($autoTeam, $slaHours) = $this->autoClassify($type);
        $dueDate = date('Y-m-d H:i:s', strtotime("+$slaHours hours"));

        // Actualizar requerimiento
        $db->query("
            UPDATE requirements 
            SET type = ?, assigned_team = ?, assigned_user_id = ?, sla_hours = ?, due_date = ?, updated_at = NOW()
            WHERE id = ?
        ", [$type, $team, $assignedUserId ?: null, $slaHours, $dueDate, $requirementId]);

        // Registrar cambios en el historial
        if ($current['type'] !== $type) {
            $this->logHistory($requirementId, $userId, 'reassigned', 'type', $current['type'], $type);
        }
        if ($current['assigned_team'] !== $team) {
            $this->logHistory($requirementId, $userId, 'reassigned', 'assigned_team', $current['assigned_team'], $team);
        }
        if ($current['assigned_user_id'] != $assignedUserId) {
            $this->logHistory($requirementId, $userId, 'reassigned', 'assigned_user_id', $current['assigned_user_id'], $assignedUserId);
        }

        // Agregar comentario con el motivo
        $db->insert('requirement_comments', [
            'requirement_id' => $requirementId,
            'user_id' => $userId,
            'comment' => "**Requerimiento reasignado:** $reason"
        ]);

        // Redirigir al detalle con mensaje de éxito
        header('Location: /requirements/view/' . $requirementId . '?success=Requerimiento reasignado correctamente');
        exit;
    }

    /**
     * Auto-clasificar según tipo
     */
    private function autoClassify($type)
    {
        $classification = [
            'incident' => ['team' => 'support', 'sla' => 4],        // Inmediato - 4 horas
            'support' => ['team' => 'support', 'sla' => 24],        // 24-48 hrs
            'improvement' => ['team' => 'automation', 'sla' => 120], // 3-5 días (72-120 hrs)
            'project_minor' => ['team' => 'automation', 'sla' => 720], // Según plan (estimado 1 mes)
            'project_major' => ['team' => 'erp_projects', 'sla' => 2160], // Según roadmap (estimado 3 meses)
        ];

        $config = $classification[$type] ?? ['team' => 'support', 'sla' => 24];
        return [$config['team'], $config['sla']];
    }

    /**
     * Generar código único de requerimiento
     */
    private function generateRequirementCode()
    {
        $prefix = 'REQ';
        $year = date('Y');
        $month = date('m');
        
        $db = Database::getInstance();
        $lastCode = $db->fetchOne("
            SELECT code FROM requirements 
            WHERE code LIKE ? 
            ORDER BY id DESC LIMIT 1
        ", ["$prefix-$year$month-%"]);

        if ($lastCode) {
            $lastNumber = intval(substr($lastCode['code'], -4));
            $newNumber = $lastNumber + 1;
        } else {
            $newNumber = 1;
        }

        return sprintf("$prefix-$year$month-%04d", $newNumber);
    }

    /**
     * Registrar en historial
     */
    private function logHistory($requirementId, $userId, $action, $fieldName = null, $oldValue = null, $newValue = null)
    {
        $db = Database::getInstance();
        $db->insert("
            INSERT INTO requirement_history (requirement_id, user_id, action, field_name, old_value, new_value)
            VALUES (?, ?, ?, ?, ?, ?)
        ", [$requirementId, $userId, $action, $fieldName, $oldValue, $newValue]);
    }

    /**
     * Obtener estadísticas
     */
    public function getStats()
    {
        $user = $_SESSION['user'] ?? [];
        $userId = $user['id'] ?? 0;
        $isAdmin = in_array($user['role_name'] ?? '', ['super_admin', 'admin']);
        
        $db = Database::getInstance();
        
        $whereClause = $isAdmin ? '1=1' : "requester_user_id = $userId";

        $stats = [
            'total' => $db->fetchOne("SELECT COUNT(*) as count FROM requirements WHERE $whereClause")['count'] ?? 0,
            'new' => $db->fetchOne("SELECT COUNT(*) as count FROM requirements WHERE status = 'new' AND $whereClause")['count'] ?? 0,
            'in_progress' => $db->fetchOne("SELECT COUNT(*) as count FROM requirements WHERE status IN ('in_analysis', 'in_development', 'in_testing') AND $whereClause")['count'] ?? 0,
            'completed' => $db->fetchOne("SELECT COUNT(*) as count FROM requirements WHERE status = 'completed' AND $whereClause")['count'] ?? 0,
        ];

        return $stats;
    }

    /**
     * Actualizar progreso automático del proyecto basado en requerimientos y backlog items
     */
    private function updateProjectProgress($project_id): void
    {
        $db = Database::getInstance();
        
        // Contar requerimientos del proyecto
        $reqStats = $db->fetchOne(
            "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed
             FROM requirements 
             WHERE project_id = ?",
            [$project_id]
        );

        // Contar backlog items del proyecto
        $backlogStats = $db->fetchOne(
            "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'done' THEN 1 ELSE 0 END) as completed
             FROM product_backlog_items 
             WHERE project_id = ?",
            [$project_id]
        );

        $totalItems = ($reqStats['total'] ?? 0) + ($backlogStats['total'] ?? 0);
        $completedItems = ($reqStats['completed'] ?? 0) + ($backlogStats['completed'] ?? 0);

        if ($totalItems > 0) {
            $progress = round(($completedItems / $totalItems) * 100);
            $db->update(
                "UPDATE projects SET progress_percentage = ? WHERE id = ?",
                [$progress, $project_id]
            );
        }
    }
}
