<?php
/**
 * Broadcast WhatsApp Management
 * Disesuaikan dengan struktur tabel broadcast_logs yang sebenarnya
 */
class Broadcast {
    /**
     * Send broadcast to multiple customers
     * Menyimpan 1 record broadcast_logs dengan total_sent & total_failed
     */
    public static function send($title, $message, $targetType, $targetData = [], $branchId = null, $userId = null) {
        try {
            $db = db();
            
            // Get customers berdasarkan target_type
            $customers = self::getTargetCustomers($targetType, $targetData, $branchId);
            
            if (empty($customers)) {
                return ['success' => false, 'error' => 'Tidak ada customer yang menjadi target'];
            }
            
            // Tambahkan footer nama cabang jika ada
            $finalMessage = $message;
            if ($branchId) {
                $stmt = $db->prepare("SELECT name FROM branches WHERE id = ?");
                $stmt->execute([$branchId]);
                $branch = $stmt->fetch();
                
                if ($branch) {
                    $finalMessage .= "\n\n─────────────\n📍 " . $branch['name'];
                }
            }
            
            // Get WhatsApp provider
            require_once __DIR__ . '/WhatsApp/WhatsAppFactory.php';
            require_once __DIR__ . '/WhatsApp/WhatsAppService.php';
            $wa = new WhatsAppService();
            
            $successCount = 0;
            $failCount = 0;
            
            // Kirim ke setiap customer
            foreach ($customers as $customer) {
                if (empty($customer['phone'])) {
                    $failCount++;
                    continue;
                }
                
                $result = $wa->sendCustomMessage($customer['phone'], $finalMessage);
                
                if ($result['success']) {
                    $successCount++;
                } else {
                    $failCount++;
                }
                
                // Delay untuk menghindari rate limit
                usleep(500000); // 0.5 detik
            }
            
            // Tentukan status broadcast
            $total = count($customers);
            if ($successCount == $total) {
                $status = 'completed';
            } elseif ($successCount > 0) {
                $status = 'partial';
            } else {
                $status = 'failed';
            }
            
            // Serialize target_data untuk disimpan
            $targetDataSerialized = json_encode($targetData);
            
            // Insert log broadcast (1 record untuk seluruh broadcast)
            $stmt = $db->prepare("
                INSERT INTO broadcast_logs 
                (branch_id, title, message, target_type, target_data, total_sent, total_failed, status, created_by, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");
            $stmt->execute([
                $branchId,
                $title,
                $finalMessage,
                $targetType,
                $targetDataSerialized,
                $successCount,
                $failCount,
                $status,
                $userId
            ]);
            
            return [
                'success' => true,
                'id' => $db->lastInsertId(),
                'total' => $total,
                'sent' => $successCount,
                'failed' => $failCount,
                'status' => $status
            ];
            
        } catch (Exception $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }
    
    /**
     * Get target customers berdasarkan target_type
     */
    private static function getTargetCustomers($targetType, $targetData, $branchId = null) {
        $db = db();
        
        switch ($targetType) {
            case 'all_customers':
                $sql = "SELECT id, name, phone, customer_number FROM customers WHERE phone IS NOT NULL AND phone != ''";
                $params = [];
                if ($branchId) {
                    $sql .= " AND branch_id = ?";
                    $params[] = $branchId;
                }
                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                return $stmt->fetchAll();
                
            case 'selected_customers':
                if (empty($targetData)) return [];
                $placeholders = implode(',', array_fill(0, count($targetData), '?'));
                $sql = "SELECT id, name, phone, customer_number FROM customers WHERE id IN ($placeholders) AND phone IS NOT NULL AND phone != ''";
                $params = $targetData;
                if ($branchId) {
                    $sql .= " AND branch_id = ?";
                    $params[] = $branchId;
                }
                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                return $stmt->fetchAll();
                
            case 'branch':
                if (empty($targetData['branch_id'])) return [];
                $stmt = $db->prepare("
                    SELECT id, name, phone, customer_number FROM customers 
                    WHERE branch_id = ? AND phone IS NOT NULL AND phone != ''
                ");
                $stmt->execute([$targetData['branch_id']]);
                return $stmt->fetchAll();
                
            case 'custom_numbers':
                if (empty($targetData['numbers'])) return [];
                $customers = [];
                foreach ($targetData['numbers'] as $phone) {
                    $customers[] = [
                        'id' => 0,
                        'name' => 'Custom',
                        'phone' => $phone,
                        'customer_number' => '-'
                    ];
                }
                return $customers;
                
            default:
                return [];
        }
    }
    
    /**
     * Get broadcast logs by branch
     */
    public static function getLogsByBranch($branchId, $limit = 50) {
        $db = db();
        $stmt = $db->prepare("
            SELECT bl.*, u.username as created_by_name
            FROM broadcast_logs bl
            LEFT JOIN users u ON bl.created_by = u.id
            WHERE bl.branch_id = ?
            ORDER BY bl.created_at DESC
            LIMIT ?
        ");
        $stmt->execute([$branchId, $limit]);
        return $stmt->fetchAll();
    }
    
    /**
     * Get all broadcast logs (for admin)
     */
    public static function getAllLogs($branchId = null, $limit = 100) {
        $db = db();
        
        $sql = "
            SELECT bl.*, u.username as created_by_name, b.name as branch_name
            FROM broadcast_logs bl
            LEFT JOIN users u ON bl.created_by = u.id
            LEFT JOIN branches b ON bl.branch_id = b.id
        ";
        
        if ($branchId) {
            $sql .= " WHERE bl.branch_id = ?";
            $stmt = $db->prepare($sql . " ORDER BY bl.created_at DESC LIMIT ?");
            $stmt->execute([$branchId, $limit]);
        } else {
            $sql .= " ORDER BY bl.created_at DESC LIMIT ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$limit]);
        }
        
        return $stmt->fetchAll();
    }
    
    /**
     * Get statistics
     */
    public static function getStats($branchId = null) {
        $db = db();
        
        $sql = "
            SELECT 
                COUNT(*) as total_broadcasts,
                SUM(total_sent) as total_sent,
                SUM(total_failed) as total_failed,
                SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_count,
                SUM(CASE WHEN status = 'partial' THEN 1 ELSE 0 END) as partial_count,
                SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_count
            FROM broadcast_logs
        ";
        
        if ($branchId) {
            $sql .= " WHERE branch_id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([$branchId]);
        } else {
            $stmt = $db->query($sql);
        }
        
        return $stmt->fetch();
    }
    
    /**
     * Get broadcast by ID
     */
    public static function find($id) {
        $db = db();
        $stmt = $db->prepare("
            SELECT bl.*, u.username as created_by_name, b.name as branch_name
            FROM broadcast_logs bl
            LEFT JOIN users u ON bl.created_by = u.id
            LEFT JOIN branches b ON bl.branch_id = b.id
            WHERE bl.id = ?
        ");
        $stmt->execute([$id]);
        return $stmt->fetch();
    }
}