#!/bin/bash

echo "========================================"
echo "DMS Sales App - Android APK Builder"
echo "========================================"
echo ""

show_menu() {
    echo "Pilih opsi build:"
    echo "1. Build APK Debug (untuk testing)"
    echo "2. Build APK Release (untuk production)"
    echo "3. Build dan Buka Android Studio"
    echo "4. Sync Capacitor saja"
    echo "5. Exit"
    echo ""
    read -p "Masukkan pilihan (1-5): " choice
    
    case $choice in
        1) build_debug ;;
        2) build_release ;;
        3) open_studio ;;
        4) sync_only ;;
        5) exit 0 ;;
        *) echo "Pilihan tidak valid!"; show_menu ;;
    esac
}

build_debug() {
    echo ""
    echo "[1/3] Building React app..."
    npm run build || { echo "Error: Build React app gagal!"; read -p "Press enter..."; show_menu; return; }
    
    echo ""
    echo "[2/3] Syncing dengan Android..."
    npx cap sync android || { echo "Error: Sync Capacitor gagal!"; read -p "Press enter..."; show_menu; return; }
    
    echo ""
    echo "[3/3] Building APK Debug..."
    cd android && ./gradlew assembleDebug && cd .. || { echo "Error: Build APK gagal!"; cd ..; read -p "Press enter..."; show_menu; return; }
    
    echo ""
    echo "========================================"
    echo "APK Debug berhasil dibuat!"
    echo "Lokasi: android/app/build/outputs/apk/debug/app-debug.apk"
    echo "========================================"
    echo ""
    read -p "Press enter to continue..."
    show_menu
}

build_release() {
    echo ""
    echo "[1/3] Building React app..."
    npm run build || { echo "Error!"; read -p "Press enter..."; show_menu; return; }
    
    echo ""
    echo "[2/3] Syncing dengan Android..."
    npx cap sync android || { echo "Error!"; read -p "Press enter..."; show_menu; return; }
    
    echo ""
    echo "[3/3] Building APK Release..."
    cd android && ./gradlew assembleRelease && cd .. || { echo "Error!"; cd ..; read -p "Press enter..."; show_menu; return; }
    
    echo ""
    echo "========================================"
    echo "APK Release berhasil dibuat!"
    echo "Lokasi: android/app/build/outputs/apk/release/app-release.apk"
    echo "========================================"
    echo ""
    read -p "Press enter to continue..."
    show_menu
}

open_studio() {
    echo ""
    echo "[1/2] Building dan Syncing..."
    npm run android:build || { echo "Error!"; read -p "Press enter..."; show_menu; return; }
    
    echo ""
    echo "[2/2] Membuka Android Studio..."
    npx cap open android
    
    echo ""
    read -p "Press enter to continue..."
    show_menu
}

sync_only() {
    echo ""
    echo "Syncing Capacitor dengan Android..."
    npx cap sync android || { echo "Error!"; read -p "Press enter..."; show_menu; return; }
    
    echo ""
    echo "Sync berhasil!"
    echo ""
    read -p "Press enter to continue..."
    show_menu
}

show_menu
