pipeline {
    agent any
    environment {
        REGISTRY = "docker.rri.co.id"
        IMAGE_NAME = "ci3-app"
        IMAGE_TAG = "latest"
        KUBE_NAMESPACE = "default"
        DEPLOYMENT_NAME = "ci3-deployment"
    }
    stages {
        stage('Checkout') {
            steps {
                git url: 'http://git.rri.co.id/admin/ci3-app.git'
            }
        }
        stage('Build Docker Image') {
            steps {
                sh "docker build -t ${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG} ."
            }
        }
        stage('Push Image') {
            steps {
                withCredentials([usernamePassword(credentialsId: 'docker-credentials', usernameVariable: 'DOCKER_USER', passwordVariable: 'DOCKER_PASS')]) {
                    sh """
                    echo \$DOCKER_PASS | docker login ${REGISTRY} -u \$DOCKER_USER --password-stdin
                    docker push ${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG}
                    """
                }
            }
        }
        stage('Deploy to Kubernetes') {
            steps {
                sh "kubectl set image deployment/${DEPLOYMENT_NAME} php=${REGISTRY}/${IMAGE_NAME}:${IMAGE_TAG} -n ${KUBE_NAMESPACE}"
            }
        }
    }
}
