<?php include __DIR__ . '/../header.php'; ?>

<?php
/**
 * $stored => integrations من DB (indexed by provider)
 */

$shippingProviders = [
    'ecotrack'   => 'ecotrack.png',
    'dhd'        => 'dhd.png',
    'zr_express' => 'zr_express.png',
    'yalidine'   => 'yalidine.png',
    'maystro'    => 'maystro.png',
];

/* ================================
   TRACKING (loaded by controller)
================================ */
$trackingStored = $trackingStored ?? [];

/* ================================
   TRACKING PROVIDERS (REAL)
================================ */
// فحص Google Sheets OAuth
$gsheetsOauthEnabled  = false;
$gsheetsOauthConnected = false;
$gsheetsEmail = '';
try {
    $_gsSettings = new \Core\App\Models\Settings();
    $gsheetsOauthEnabled   = $_gsSettings->get('gsheets_oauth_enabled', '0') === '1';
    $gsheetsOauthConnected = !empty($_gsSettings->get('gsheets_oauth_refresh_token', ''));
    $gsheetsEmail          = $_gsSettings->get('gsheets_oauth_connected_email', '');
} catch (\Throwable $e) {}

/* ================================
   VIDEO MEETING (new)
================================ */
$videoActive = false;
$videoProvider = '';
try {
    $vmRow = \db()->query("SELECT provider FROM video_meeting_settings WHERE is_active=1 LIMIT 1")->fetch(\PDO::FETCH_ASSOC);
    if ($vmRow) { $videoActive = true; $videoProvider = $vmRow['provider']; }
} catch (\Throwable $e) {}

$trackingProviders = [
    'google_sheets' => [
        'image'    => 'google-sheets.png',
        'url'      => '/admin/settings/gsheets',
        'active'   => $gsheetsOauthEnabled && $gsheetsOauthConnected,
        'label'    => 'Google Sheets',
        'subtitle' => $gsheetsOauthConnected ? ($gsheetsEmail ?: __('gsheets.connected_label','Connected')) : __('gsheets.not_connected','Not connected'),
    ],
    'gemini' => [
        'image'  => 'ai.png',
        'url'    => '/admin/settings/ai',
        'active' => true,
    ],
    'ga4' => [
        'image'  => 'google-analytics.png',
        'url'    => '/admin/settings/ga4',
        'active' => !empty($trackingStored['ga4']),
    ],
    'facebook_pixel' => [
        'image'  => 'facebook-pixel.png',
        'url'    => '/admin/settings/facebook-pixel',
        'active' => !empty($trackingStored['facebook_pixel']),
    ],
    'tiktok_pixel' => [
        'image'  => 'tiktok.png',
        'url'    => '/admin/settings/tiktok-pixel',
        'active' => !empty($trackingStored['tiktok_pixel']),
    ],
    'gtm' => [
        'image'  => 'gtm.png',
        'url'    => '/admin/settings/gtm',
        'active' => !empty($trackingStored['gtm']),
    ],
    'whatsapp' => [
        'image'  => 'whatsapp.png',
        'url'    => '/admin/settings/whatsapp',
        'active' => !empty($trackingStored['whatsapp']),
    ],
];
?>

<style>
.integration-card {
    height: 260px;
    border-radius: 16px;
    overflow: hidden;
    background: #ffffff;
    border: 1px solid rgba(0,0,0,.08);
    box-shadow: 0 4px 12px rgba(0,0,0,.06);
    position: relative;
    transition: all .35s ease;
}

.integration-card:hover {
    transform: translateY(-6px);
    box-shadow: 0 14px 36px rgba(0,0,0,.15);
    border-color: rgba(0,0,0,.15);
}

.integration-card img {
    max-width: 85%;
    max-height: 140px;
    object-fit: contain;
    opacity: .9;
    transition: all .35s ease;
}

.integration-card:hover img {
    opacity: 1;
    transform: scale(1.05);
}

.integration-footer {
    position: absolute;
    bottom: 14px;
    left: 14px;
    right: 14px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.integration-badge {
    font-size: 12px;
}
</style>

<div class="container py-4">

    <!-- PAGE HEADER -->
    <div class="mb-4">
        <h3 class="mb-1">
            <i class="bi bi-plug me-2"></i>
            <?= __('integrations.title', 'Integrations') ?>
        </h3>
        <small class="text-muted">
            <?= __('sidebar.manage_site', 'Manage Site') ?>
            →
            <?= __('integrations.title', 'Integrations') ?>
        </small>
    </div>

    <!-- TABS -->
    <?php $activeTab = $_GET['tab'] ?? 'shipping'; ?>
    <ul class="nav nav-tabs mb-4" role="tablist">
        <li class="nav-item">
            <button class="nav-link <?= $activeTab === 'shipping' ? 'active' : '' ?>"
                    data-bs-toggle="tab"
                    data-bs-target="#shipping"
                    type="button">
                <i class="bi bi-truck me-1"></i>
                <?= __('integrations.shipping', 'Shipping Companies') ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link <?= $activeTab === 'tracking' ? 'active' : '' ?>"
                    data-bs-toggle="tab"
                    data-bs-target="#tracking"
                    type="button">
                <i class="bi bi-graph-up me-1"></i>
                <?= __('integrations.tracking', 'Tracking & Pixels') ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link <?= $activeTab === 'team' ? 'active' : '' ?>"
                    data-bs-toggle="tab"
                    data-bs-target="#team-tab"
                    type="button">
                <i class="bi bi-people-fill me-1"></i>
                <?= __('integrations.team', 'Team & Communication') ?>
                <?php if ($videoActive): ?>
                <span class="badge bg-success-subtle text-success border border-success-subtle ms-1" style="font-size:.62rem">
                    <?= __('integrations.active','Active') ?>
                </span>
                <?php endif; ?>
            </button>
        </li>
    </ul>

    <div class="tab-content">

        <!-- ===================== -->
        <!-- SHIPPING (UNCHANGED) -->
        <!-- ===================== -->
        <div class="tab-pane fade <?= $activeTab === 'shipping' ? 'show active' : '' ?>" id="shipping">
            <div class="row g-4">
                <?php foreach ($shippingProviders as $key => $image): ?>
                    <?php
                    $row      = $stored[$key] ?? null;
                    $isActive = isset($row['is_active']) && (int)$row['is_active'] === 1;
                    ?>
                    <div class="col-md-6 col-lg-4">
                        <div class="integration-card d-flex align-items-center justify-content-center">
                            <img src="/admin/assets/img/<?= htmlspecialchars($image) ?>"
                                 alt="<?= htmlspecialchars($key) ?>">
                            <div class="integration-footer">
                                <?php if ($isActive): ?>
                                    <span class="badge bg-success integration-badge">
                                        <?= __('integrations.active', 'Active') ?>
                                    </span>
                                <?php else: ?>
                                    <span class="badge bg-secondary integration-badge">
                                        <?= __('integrations.not_configured', 'Not configured') ?>
                                    </span>
                                <?php endif; ?>
                                <a href="/admin/integrations/configure?provider=<?= urlencode($key) ?>"
                                   class="btn btn-sm btn-outline-primary">
                                    <?= __('integrations.configure', 'Configure') ?>
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- ===================== -->
        <!-- TRACKING (REAL) -->
        <!-- ===================== -->
        <div class="tab-pane fade <?= $activeTab === 'tracking' ? 'show active' : '' ?>" id="tracking">
            <div class="row g-4">
                <?php foreach ($trackingProviders as $key => $provider): ?>
                    <div class="col-md-6 col-lg-4">
                        <div class="integration-card d-flex flex-column align-items-center justify-content-center">

                            <img src="/admin/assets/img/<?= htmlspecialchars($provider['image']) ?>"
                                 alt="<?= htmlspecialchars($key) ?>">

                            <?php if (!empty($provider['label'])): ?>
                                <div class="mt-2 fw-semibold small text-center"><?= htmlspecialchars($provider['label']) ?></div>
                            <?php endif; ?>

                            <?php if (!empty($provider['subtitle'])): ?>
                                <div class="text-muted" style="font-size:.75rem"><?= htmlspecialchars($provider['subtitle']) ?></div>
                            <?php endif; ?>

                            <div class="integration-footer">

                                <?php if ($provider['active']): ?>
                                    <span class="badge bg-success integration-badge">
                                        <i class="bi bi-check-circle me-1"></i><?= __('integrations.active', 'Active') ?>
                                    </span>
                                <?php else: ?>
                                    <span class="badge bg-secondary integration-badge">
                                        <?= __('integrations.not_configured', 'Not configured') ?>
                                    </span>
                                <?php endif; ?>

                                <a href="<?= htmlspecialchars($provider['url']) ?>"
                                   class="btn btn-sm btn-outline-primary">
                                    <i class="bi bi-gear me-1"></i><?= __('integrations.configure', 'Configure') ?>
                                </a>

                            </div>

                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- ══════════════════════════════════
             TEAM & COMMUNICATION TAB
        ══════════════════════════════════ -->
        <div class="tab-pane fade <?= $activeTab === 'team' ? 'show active' : '' ?>" id="team-tab">
            <div class="row g-4">

                <!-- Video Meeting Card -->
                <div class="col-md-6 col-lg-4">
                    <div class="integration-card d-flex flex-column align-items-center justify-content-center position-relative">

                        <!-- Icon area -->
                        <div class="d-flex align-items-center justify-content-center mb-2"
                             style="width:72px;height:72px;border-radius:18px;background:rgba(13,110,253,.08)">
                            <i class="bi bi-camera-video-fill text-primary" style="font-size:2rem"></i>
                        </div>
                        <div class="fw-bold small mb-1"><?= __('video_meeting.title','Video Meeting') ?></div>
                        <div class="text-muted text-center px-2" style="font-size:.73rem;line-height:1.5">
                            <?= __('video_meeting.card_desc','Add Jitsi, Daily.co or Whereby video calls to your team meetings') ?>
                        </div>

                        <?php if ($videoActive): ?>
                        <div class="mt-2">
                            <span class="badge bg-success-subtle text-success border border-success-subtle" style="font-size:.7rem">
                                <i class="bi bi-check-circle me-1"></i><?= __('integrations.active','Active') ?>
                                <?php
                                $vpLabels = ['jitsi'=>'Jitsi','daily'=>'Daily.co','whereby'=>'Whereby'];
                                if ($videoProvider) echo ' — ' . ($vpLabels[$videoProvider] ?? $videoProvider);
                                ?>
                            </span>
                        </div>
                        <?php endif; ?>

                        <div class="integration-footer">
                            <?php if ($videoActive): ?>
                            <span class="badge bg-success integration-badge">
                                <i class="bi bi-check-circle me-1"></i><?= __('integrations.active','Active') ?>
                            </span>
                            <?php else: ?>
                            <span class="badge bg-secondary integration-badge">
                                <?= __('integrations.not_configured','Not configured') ?>
                            </span>
                            <?php endif; ?>
                            <a href="/admin/integrations/video-meeting"
                               class="btn btn-sm btn-outline-primary">
                                <i class="bi bi-gear me-1"></i><?= __('integrations.configure','Configure') ?>
                            </a>
                        </div>

                    </div>
                </div>

            </div>
        </div>

    </div><!-- /.tab-content -->

</div>

<?php include __DIR__ . '/../footer.php'; ?>