<?php
// Helper class for platform management
class PlatformManager {
    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
    }

    public function getAllPlatforms() {
        try {
            $query = "SELECT * FROM external_platforms ORDER BY region, name";
            $stmt = $this->db->prepare($query);
            $stmt->execute();
            return $stmt->fetchAll();
        } catch (Exception $e) {
            error_log("Get all platforms error: " . $e->getMessage());
            return [];
        }
    }

    public function updatePlatform($id, $api_key, $username, $password, $is_active) {
        try {
            $query = "UPDATE external_platforms
                      SET api_key = :api_key, username = :username, password = :password, is_active = :is_active
                      WHERE id = :id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id', $id);
            $stmt->bindParam(':api_key', $api_key);
            $stmt->bindParam(':username', $username);
            $stmt->bindParam(':password', $password);
            $stmt->bindParam(':is_active', $is_active);
            return $stmt->execute();
        } catch (Exception $e) {
            error_log("Update platform error: " . $e->getMessage());
            return false;
        }
    }
}

$platformManager = new PlatformManager();
$publisher = new Publisher();
$message = '';
$error = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'update_platform':
                $id = (int)$_POST['id'];
                $api_key = sanitize_input($_POST['api_key']);
                $username = sanitize_input($_POST['username']);
                $password = sanitize_input($_POST['password']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;

                if ($platformManager->updatePlatform($id, $api_key, $username, $password, $is_active)) {
                    $message = __('platform_updated_successfully') ?? 'Platform updated successfully';
                } else {
                    $error = __('platform_update_failed') ?? 'Failed to update platform';
                }
                break;

            case 'test_publish':
                $articleId = (int)$_POST['article_id'];
                $result = $publisher->publishToExternalPlatforms($articleId);

                if ($result) {
                    $message = __('test_publish_successful') ?? 'Test publishing completed';
                } else {
                    $error = __('test_publish_failed') ?? 'Test publishing failed';
                }
                break;

            case 'retry_failed':
                $retryCount = $publisher->retryFailedPublishing();
                $message = sprintf(__('retry_completed') ?? 'Retried %d failed publications', $retryCount);
                break;
        }
    }
}

$platforms = $platformManager->getAllPlatforms();
$publishingHistory = $publisher->getPublishingHistory();

// Get recent published articles for testing
$article = new Article();
$recentArticles = $article->getAll('external', 5, 0, null, 'published', '');
?>

<div class="row">
    <div class="col-lg-8">
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></i> <?= htmlspecialchars($message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($error) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="fas fa-globe"></i> <?= __('international_platforms') ?? 'International Publishing Platforms' ?>
                </h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th><?= __('platform') ?? 'Platform' ?></th>
                                <th><?= __('region') ?? 'Region' ?></th>
                                <th><?= __('status') ?? 'Status' ?></th>
                                <th><?= __('credentials') ?? 'Credentials' ?></th>
                                <th><?= __('actions') ?? 'Actions' ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($platforms as $platform): ?>
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <i class="fas fa-external-link-alt text-primary me-2"></i>
                                            <div>
                                                <strong><?= htmlspecialchars($platform['name']) ?></strong>
                                                <?php if ($platform['api_endpoint']): ?>
                                                    <br><small class="text-muted"><?= htmlspecialchars($platform['api_endpoint']) ?></small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <?php
                                        $regionColors = [
                                            'america' => 'primary',
                                            'europe' => 'success',
                                            'asia' => 'warning',
                                            'global' => 'info'
                                        ];
                                        $regionLabels = [
                                            'america' => 'Americas',
                                            'europe' => 'Europe',
                                            'asia' => 'Asia',
                                            'global' => 'Global'
                                        ];
                                        ?>
                                        <span class="badge bg-<?= $regionColors[$platform['region']] ?? 'secondary' ?>">
                                            <?= $regionLabels[$platform['region']] ?? ucfirst($platform['region']) ?>
                                        </span>
                                    </td>
                                    <td>
                                        <span class="badge <?= $platform['is_active'] ? 'bg-success' : 'bg-secondary' ?>">
                                            <?= $platform['is_active'] ? (__('active') ?? 'Active') : (__('inactive') ?? 'Inactive') ?>
                                        </span>
                                    </td>
                                    <td>
                                        <?php if ($platform['api_key'] || $platform['username']): ?>
                                            <i class="fas fa-check text-success" title="<?= __('configured') ?? 'Configured' ?>"></i>
                                        <?php else: ?>
                                            <i class="fas fa-times text-danger" title="<?= __('not_configured') ?? 'Not Configured' ?>"></i>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#configModal<?= $platform['id'] ?>">
                                            <i class="fas fa-cog"></i> <?= __('configure') ?? 'Configure' ?>
                                        </button>
                                    </td>
                                </tr>

                                <!-- Configuration Modal -->
                                <div class="modal fade" id="configModal<?= $platform['id'] ?>" tabindex="-1">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title"><?= __('configure_platform') ?? 'Configure Platform' ?>: <?= htmlspecialchars($platform['name']) ?></h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <form method="POST">
                                                <div class="modal-body">
                                                    <input type="hidden" name="action" value="update_platform">
                                                    <input type="hidden" name="id" value="<?= $platform['id'] ?>">

                                                    <div class="mb-3">
                                                        <label class="form-label"><?= __('api_key') ?? 'API Key' ?></label>
                                                        <input type="password" class="form-control" name="api_key"
                                                               value="<?= htmlspecialchars($platform['api_key'] ?? '') ?>"
                                                               placeholder="<?= __('enter_api_key') ?? 'Enter API key' ?>">
                                                    </div>

                                                    <div class="mb-3">
                                                        <label class="form-label"><?= __('username') ?? 'Username' ?></label>
                                                        <input type="text" class="form-control" name="username"
                                                               value="<?= htmlspecialchars($platform['username'] ?? '') ?>"
                                                               placeholder="<?= __('enter_username') ?? 'Enter username' ?>">
                                                    </div>

                                                    <div class="mb-3">
                                                        <label class="form-label"><?= __('password') ?? 'Password' ?></label>
                                                        <input type="password" class="form-control" name="password"
                                                               value="<?= htmlspecialchars($platform['password'] ?? '') ?>"
                                                               placeholder="<?= __('enter_password') ?? 'Enter password' ?>">
                                                    </div>

                                                    <div class="form-check">
                                                        <input class="form-check-input" type="checkbox" name="is_active" value="1"
                                                               <?= $platform['is_active'] ? 'checked' : '' ?>>
                                                        <label class="form-check-label">
                                                            <?= __('enable_platform') ?? 'Enable this platform' ?>
                                                        </label>
                                                    </div>
                                                </div>
                                                <div class="modal-footer">
                                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= __('cancel') ?? 'Cancel' ?></button>
                                                    <button type="submit" class="btn btn-primary"><?= __('save_configuration') ?? 'Save Configuration' ?></button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <div class="card mt-4">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-history"></i> <?= __('publishing_history') ?? 'Publishing History' ?>
                </h6>
            </div>
            <div class="card-body">
                <?php if (empty($publishingHistory)): ?>
                    <div class="text-center py-4">
                        <i class="fas fa-globe fa-3x text-muted mb-3"></i>
                        <h6 class="text-muted"><?= __('no_publishing_history') ?? 'No publishing history yet' ?></h6>
                        <p class="text-muted"><?= __('publish_articles_message') ?? 'Articles will appear here after being published to external platforms' ?></p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead>
                                <tr>
                                    <th><?= __('article') ?? 'Article' ?></th>
                                    <th><?= __('platform') ?? 'Platform' ?></th>
                                    <th><?= __('status') ?? 'Status' ?></th>
                                    <th><?= __('published_at') ?? 'Published At' ?></th>
                                    <th><?= __('external_link') ?? 'External Link' ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach (array_slice($publishingHistory, 0, 10) as $history): ?>
                                    <tr>
                                        <td><?= htmlspecialchars(substr($history['article_title'], 0, 50)) ?>...</td>
                                        <td><?= htmlspecialchars($history['platform_name']) ?></td>
                                        <td>
                                            <span class="badge <?= $history['status'] === 'published' ? 'bg-success' : 'bg-danger' ?>">
                                                <?= ucfirst($history['status']) ?>
                                            </span>
                                        </td>
                                        <td><?= date('M j, H:i', strtotime($history['published_at'])) ?></td>
                                        <td>
                                            <?php if ($history['external_url']): ?>
                                                <a href="<?= htmlspecialchars($history['external_url']) ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                                    <i class="fas fa-external-link-alt"></i>
                                                </a>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-chart-pie"></i> <?= __('publishing_statistics') ?? 'Publishing Statistics' ?>
                </h6>
            </div>
            <div class="card-body">
                <div class="row text-center">
                    <div class="col-6 mb-3">
                        <div class="h4 mb-1 text-primary"><?= count($platforms) ?></div>
                        <small class="text-muted"><?= __('total_platforms') ?? 'Total Platforms' ?></small>
                    </div>
                    <div class="col-6 mb-3">
                        <div class="h4 mb-1 text-success"><?= array_sum(array_column($platforms, 'is_active')) ?></div>
                        <small class="text-muted"><?= __('active_platforms') ?? 'Active Platforms' ?></small>
                    </div>
                    <div class="col-6">
                        <div class="h4 mb-1 text-info"><?= count($publishingHistory) ?></div>
                        <small class="text-muted"><?= __('total_publications') ?? 'Total Publications' ?></small>
                    </div>
                    <div class="col-6">
                        <div class="h4 mb-1 text-warning">
                            <?php
                            $successCount = count(array_filter($publishingHistory, function($h) { return $h['status'] === 'published'; }));
                            echo count($publishingHistory) > 0 ? round(($successCount / count($publishingHistory)) * 100) : 0;
                            ?>%
                        </div>
                        <small class="text-muted"><?= __('success_rate') ?? 'Success Rate' ?></small>
                    </div>
                </div>
            </div>
        </div>

        <div class="card mt-3">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-rocket"></i> <?= __('quick_actions') ?? 'Quick Actions' ?>
                </h6>
            </div>
            <div class="card-body">
                <?php if (!empty($recentArticles)): ?>
                    <div class="mb-3">
                        <label class="form-label"><?= __('test_publish') ?? 'Test Publish Article' ?></label>
                        <form method="POST" class="d-flex gap-2">
                            <input type="hidden" name="action" value="test_publish">
                            <select name="article_id" class="form-select form-select-sm">
                                <?php foreach ($recentArticles as $art): ?>
                                    <option value="<?= $art['id'] ?>"><?= htmlspecialchars(substr($art['title'], 0, 40)) ?>...</option>
                                <?php endforeach; ?>
                            </select>
                            <button type="submit" class="btn btn-sm btn-primary">
                                <i class="fas fa-paper-plane"></i>
                            </button>
                        </form>
                    </div>
                <?php endif; ?>

                <form method="POST" class="mb-3">
                    <input type="hidden" name="action" value="retry_failed">
                    <button type="submit" class="btn btn-warning w-100">
                        <i class="fas fa-redo"></i> <?= __('retry_failed_publications') ?? 'Retry Failed Publications' ?>
                    </button>
                </form>

                <div class="small text-muted">
                    <p><strong><?= __('note') ?? 'Note' ?>:</strong></p>
                    <ul class="mb-0">
                        <li><?= __('platform_note_1') ?? 'Configure API credentials for each platform' ?></li>
                        <li><?= __('platform_note_2') ?? 'Only external articles are published automatically' ?></li>
                        <li><?= __('platform_note_3') ?? 'Failed publications can be retried manually' ?></li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="card mt-3">
            <div class="card-header">
                <h6 class="card-title mb-0">
                    <i class="fas fa-map-marked-alt"></i> <?= __('regional_coverage') ?? 'Regional Coverage' ?>
                </h6>
            </div>
            <div class="card-body">
                <?php
                $regionCounts = array_count_values(array_column($platforms, 'region'));
                $regionLabels = [
                    'america' => 'Americas',
                    'europe' => 'Europe',
                    'asia' => 'Asia',
                    'global' => 'Global'
                ];
                ?>
                <?php
                $regionColors = [
                    'america' => 'primary',
                    'europe' => 'success',
                    'asia' => 'warning',
                    'global' => 'info'
                ];
                foreach ($regionCounts as $region => $count): ?>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="badge bg-<?= $regionColors[$region] ?? 'secondary' ?>">
                            <?= $regionLabels[$region] ?? ucfirst($region) ?>
                        </span>
                        <span class="fw-bold"><?= $count ?> platforms</span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>