<?php
// Enable error reporting untuk debug
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);

// Set JSON header di awal
header('Content-Type: application/json');

try {
    // Load required files
    require_once __DIR__ . '/../includes/auth.php';
    require_once __DIR__ . '/../includes/functions.php';
    
    // Check if user is logged in
    if (!isset($_SESSION['user_id'])) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Unauthorized - Please login']);
        exit;
    }
    
    // Load WhatsApp classes
    $waFactoryPath = __DIR__ . '/../classes/WhatsApp/WhatsAppFactory.php';
    $waServicePath = __DIR__ . '/../classes/WhatsApp/WhatsAppService.php';
    
    if (!file_exists($waFactoryPath) || !file_exists($waServicePath)) {
        throw new Exception('WhatsApp classes not found. Please check files exist.');
    }
    
    require_once $waFactoryPath;
    require_once $waServicePath;
    
    // Get action
    $action = $_GET['action'] ?? '';
    
    // Create WhatsApp service
    $wa = new WhatsAppService();
    
    // Handle actions
    switch ($action) {
        case 'status':
            try {
                $status = $wa->getStatus();
                $connected = $wa->isConnected();
                
                // Get provider name safely
                $providerName = 'unknown';
                if (method_exists($wa, 'getProviderName')) {
                    $providerName = $wa->getProviderName();
                } else {
                    // Fallback: get from factory
                    if (class_exists('WhatsAppFactory')) {
                        $providerName = WhatsAppFactory::getActiveProvider();
                    }
                }
                
                echo json_encode([
                    'success' => true,
                    'connected' => $connected,
                    'provider' => $providerName,
                    'data' => $status
                ]);
            } catch (\Throwable $e) {
                echo json_encode([
                    'success' => false,
                    'connected' => false,
                    'error' => $e->getMessage()
                ]);
            }
            break;
            
        case 'get_qr':
            try {
                $qr = $wa->getQRCode();
                
                if ($qr) {
                    echo json_encode([
                        'success' => true,
                        'qr' => $qr
                    ]);
                } else {
                    echo json_encode([
                        'success' => false,
                        'error' => 'QR Code tidak tersedia. Pastikan server Baileys sudah berjalan dan belum terhubung.'
                    ]);
                }
            } catch (\Throwable $e) {
                echo json_encode([
                    'success' => false,
                    'error' => 'Error getting QR: ' . $e->getMessage()
                ]);
            }
            break;
            
        default:
            echo json_encode([
                'success' => false,
                'error' => 'Invalid action. Use: status or get_qr'
            ]);
    }
    
} catch (\Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => 'Server error: ' . $e->getMessage(),
        'file' => basename($e->getFile()),
        'line' => $e->getLine()
    ]);
}