<?php
/**
 * Google Sheets OAuth2 Settings Page
 * Variables: $clientId, $clientSecret, $isConnected, $isConfigured,
 *            $connectedEmail, $spreadsheetId, $sheetName, $startRow,
 *            $mergeVariants, $isEnabled
 */
?>

<div class="content-wrapper">
<section class="content pt-3">
<div class="container-fluid pb-5">

    <!-- Header -->
    <div class="d-flex justify-content-between align-items-start mb-4">
        <div>
            <h3 class="mb-1 fw-bold">
                <img src="https://www.gstatic.com/images/branding/product/2x/sheets_2020q4_48dp.png"
                     style="width:28px;height:28px;vertical-align:middle" class="me-2" alt="Sheets">
                <?= __('gsheets.title','Google Sheets') ?>
                <?php if ($isConfigured): ?>
                    <span class="badge bg-success ms-2" style="font-size:.7rem;vertical-align:middle">
                        <i class="bi bi-check-circle me-1"></i><?= __('gsheets.active','Active') ?>
                    </span>
                <?php endif; ?>
            </h3>
            <p class="text-muted mb-0 small">
                <?= __('gsheets.subtitle','Export confirmed orders automatically to Google Sheets') ?>
            </p>
        </div>
        <div class="d-flex gap-2">
            <a href="/admin/settings/gsheets/monitor" class="btn btn-sm btn-success">
                <i class="bi bi-activity me-1"></i>
                <?= __('gsheets.monitor_btn', 'Queue Monitor') ?>
            </a>
            <a href="/admin/integrations?tab=tracking" class="btn btn-sm btn-outline-secondary">
                <i class="bi bi-arrow-right me-1"></i>
                <?= __('integrations.title','Integrations') ?>
            </a>
        </div>
    </div>

    <?php if (!empty($_SESSION['flash_success'])): ?>
        <div class="alert alert-success alert-dismissible fade show py-2">
            <i class="bi bi-check-circle me-1"></i><?= htmlspecialchars($_SESSION['flash_success']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['flash_success']); ?>
    <?php endif; ?>

    <?php if (!empty($_SESSION['flash_error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show py-2">
            <i class="bi bi-exclamation-triangle me-1"></i><?= htmlspecialchars($_SESSION['flash_error']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php unset($_SESSION['flash_error']); ?>
    <?php endif; ?>

    <!-- ══════════════════════════════════════════════
         STEP 1 — Google Cloud Credentials
    ══════════════════════════════════════════════ -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-header bg-white border-bottom py-3">
            <h6 class="mb-0 fw-semibold">
                <span class="badge bg-primary rounded-circle me-2"
                      style="width:22px;height:22px;line-height:15px">
                    <?= !empty($clientId) ? '<i class="bi bi-check" style="font-size:.7rem"></i>' : '1' ?>
                </span>
                <?= __('gsheets.step1_title','Google Cloud Credentials') ?>
                <small class="text-muted fw-normal ms-2"><?= __('gsheets.step1_desc','Create OAuth2 credentials in Google Cloud Console') ?></small>
            </h6>
        </div>
        <div class="card-body">
            <!-- Callout -->
            <div class="rounded-3 p-3 mb-4 small"
                 style="background:#e8f0fe;border-left:4px solid #1a73e8;color:#174ea6">
                <strong><?= __('gsheets.how_to','How to get credentials:') ?></strong><br>
                1. <?= __('gsheets.step_cloud','Go to') ?>
                   <a href="https://console.cloud.google.com/apis/credentials" target="_blank"
                      class="fw-semibold" style="color:#174ea6">
                       Google Cloud Console → Credentials
                   </a><br>
                2. <?= __('gsheets.step_create','Create → OAuth 2.0 Client ID → Web Application') ?><br>
                3. <?= __('gsheets.step_redirect','Add Authorized redirect URI:') ?>
                   <code class="ms-1 px-2 py-1 bg-white rounded border" style="color:#c53030"><?=
                       ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http')
                       . '://' . ($_SERVER['HTTP_HOST'] ?? 'yourdomain.com')
                       . '/admin/settings/gsheets/callback'
                   ?></code><br>
                4. <?= __('gsheets.step_enable_api','Enable Google Sheets API + Google Drive API') ?>
            </div>

            <form method="POST" action="/admin/settings/gsheets/save-credentials">
                <?= \Core\System\Csrf::field() ?>
                <div class="row g-3">
                    <div class="col-lg-6">
                        <label class="form-label fw-semibold small">Client ID *</label>
                        <input type="text" name="client_id" class="form-control font-monospace"
                               value="<?= htmlspecialchars($clientId) ?>"
                               placeholder="xxxxxxx.apps.googleusercontent.com">
                    </div>
                    <div class="col-lg-6">
                        <label class="form-label fw-semibold small">Client Secret *</label>
                        <div class="input-group">
                            <input type="password" name="client_secret" id="clientSecretInput"
                                   class="form-control font-monospace"
                                   value="<?= htmlspecialchars($clientSecret) ?>"
                                   placeholder="GOCSPX-...">
                            <button type="button" class="btn btn-outline-secondary px-3"
                                    onclick="toggleSecret()" tabindex="-1">
                                <i class="bi bi-eye" id="secretEyeIcon"></i>
                            </button>
                        </div>
                    </div>
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary px-4">
                            <i class="bi bi-save me-1"></i>
                            <?= __('gsheets.save_credentials','Save Credentials') ?>
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- ══════════════════════════════════════════════
         STEP 2 — Connect Google Account
    ══════════════════════════════════════════════ -->
    <div class="card border-0 shadow-sm mb-4 <?= empty($clientId) ? 'opacity-50' : '' ?>">
        <div class="card-header bg-white border-bottom py-3">
            <h6 class="mb-0 fw-semibold">
                <span class="badge <?= $isConnected ? 'bg-success' : 'bg-primary' ?> rounded-circle me-2"
                      style="width:22px;height:22px;line-height:15px">
                    <?= $isConnected ? '<i class="bi bi-check" style="font-size:.7rem"></i>' : '2' ?>
                </span>
                <?= __('gsheets.step2_title','Connect Google Account') ?>
                <small class="text-muted fw-normal ms-2"><?= __('gsheets.step2_desc','Authorize access to your Google Sheets') ?></small>
            </h6>
        </div>
        <div class="card-body">
            <?php if ($isConnected): ?>
                <div class="d-flex align-items-center gap-3 flex-wrap">
                    <div class="d-flex align-items-center gap-2 px-3 py-2 rounded-pill border border-success bg-success-subtle">
                        <i class="bi bi-google text-success"></i>
                        <span class="fw-semibold text-success small">
                            <?= !empty($connectedEmail) ? htmlspecialchars($connectedEmail) : __('gsheets.connected_label','Google Account Connected') ?>
                        </span>
                        <i class="bi bi-check-circle-fill text-success"></i>
                    </div>
                    <form method="post" action="/admin/settings/gsheets/disconnect" style="display:inline">
                                    <?= \Core\System\Csrf::field() ?>
                                    <button type="submit" class="btn btn-sm btn-outline-danger">')">
                        <i class="bi bi-x-circle me-1"></i><?= __('gsheets.disconnect','Disconnect') ?></button>
                                </form>
                </div>
            <?php else: ?>
                <a href="/admin/settings/gsheets/connect"
                   class="d-inline-flex align-items-center gap-2 px-4 py-2 rounded-3 text-decoration-none fw-semibold <?= empty($clientId) ? 'pe-none' : '' ?>"
                   style="background:#fff;border:1px solid #dadce0;color:#3c4043;transition:box-shadow .2s"
                   onmouseover="this.style.boxShadow='0 2px 8px rgba(0,0,0,.15)'"
                   onmouseout="this.style.boxShadow='none'">
                    <svg viewBox="0 0 24 24" width="20" height="20">
                        <path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
                        <path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
                        <path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
                        <path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
                    </svg>
                    <?= __('gsheets.sign_in_google','Sign in with Google') ?>
                </a>
            <?php endif; ?>
        </div>
    </div>

    <!-- ══════════════════════════════════════════════
         STEP 3 — Sheet Configuration
    ══════════════════════════════════════════════ -->
    <div class="card border-0 shadow-sm mb-4 <?= !$isConnected ? 'opacity-50' : '' ?>">
        <div class="card-header bg-white border-bottom py-3">
            <h6 class="mb-0 fw-semibold">
                <span class="badge <?= $isConfigured ? 'bg-success' : 'bg-primary' ?> rounded-circle me-2"
                      style="width:22px;height:22px;line-height:15px">
                    <?= $isConfigured ? '<i class="bi bi-check" style="font-size:.7rem"></i>' : '3' ?>
                </span>
                <?= __('gsheets.step3_title','Select Sheet') ?>
                <small class="text-muted fw-normal ms-2"><?= __('gsheets.step3_desc','Choose which spreadsheet and sheet to export orders to') ?></small>
            </h6>
        </div>
        <div class="card-body <?= !$isConnected ? 'pe-none' : '' ?>">
            <form method="POST" action="/admin/settings/gsheets/save-config">
                <?= \Core\System\Csrf::field() ?>

                <div class="row g-3 mb-4">
                    <!-- اختيار الملف -->
                    <div class="col-lg-4">
                        <label class="form-label fw-semibold small">
                            <i class="bi bi-folder me-1 text-muted"></i>
                            <?= __('gsheets.select_file','Spreadsheet File') ?> *
                        </label>
                        <select id="fileSelect" name="spreadsheet_id" class="form-select"
                                onchange="loadSheets(this.value)"
                                <?= !$isConnected ? 'disabled' : '' ?>>
                            <option value=""><?= __('gsheets.select_file_placeholder','Select...') ?></option>
                            <?php if (!empty($spreadsheetId)): ?>
                                <option value="<?= htmlspecialchars($spreadsheetId) ?>" selected>
                                    <?= htmlspecialchars($spreadsheetId) ?>
                                </option>
                            <?php endif; ?>
                        </select>
                        <?php if ($isConnected): ?>
                            <button type="button" class="btn btn-link btn-sm px-0 mt-1"
                                    onclick="loadFiles()">
                                <i class="bi bi-arrow-clockwise me-1"></i><?= __('gsheets.load_files','Load my files') ?>
                            </button>
                        <?php endif; ?>
                    </div>

                    <!-- اختيار الـ Sheet Tab -->
                    <div class="col-lg-4">
                        <label class="form-label fw-semibold small">
                            <i class="bi bi-table me-1 text-muted"></i>
                            <?= __('gsheets.select_sheet','Sheet Tab') ?> *
                        </label>
                        <select id="sheetSelect" name="sheet_name" class="form-select"
                                <?= !$isConnected ? 'disabled' : '' ?>>
                            <option value=""><?= __('gsheets.select_sheet_placeholder','Select...') ?></option>
                            <?php if (!empty($sheetName)): ?>
                                <option value="<?= htmlspecialchars($sheetName) ?>" selected>
                                    <?= htmlspecialchars($sheetName) ?>
                                </option>
                            <?php endif; ?>
                        </select>
                    </div>

                    <!-- رقم السطر -->
                    <div class="col-lg-4">
                        <label class="form-label fw-semibold small">
                            <i class="bi bi-123 me-1 text-muted"></i>
                            <?= __('gsheets.start_row','Start from row') ?>
                        </label>
                        <input type="number" name="start_row" class="form-control"
                               value="<?= (int)$startRow ?: 2 ?>" min="1" max="100"
                               <?= !$isConnected ? 'disabled' : '' ?>>
                        <div class="form-text"><?= __('gsheets.start_row_hint','Row 2 = after header row') ?></div>
                    </div>

                    <!-- دمج المتغيرات -->
                    <div class="col-12">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="merge_variants"
                                   id="mergeVariants" value="1"
                                   <?= $mergeVariants ? 'checked' : '' ?>
                                   <?= !$isConnected ? 'disabled' : '' ?>>
                            <label class="form-check-label small fw-semibold" for="mergeVariants">
                                <?= __('gsheets.merge_variants','Merge variants (size/color) with product name') ?>
                            </label>
                        </div>
                    </div>

                    <!-- وضع التصدير: كل الطلبات أم المؤكدة فقط -->
                    <div class="col-12 mt-3">
                        <label class="form-label fw-semibold">
                            <i class="bi bi-filter-circle me-1 text-primary"></i>
                            <?= __('gsheets.export_mode', 'Export Mode') ?>
                        </label>
                        <?php
                        $exportMode = \Core\App\Models\Settings::getStatic('gsheets_export_mode', 'confirmed_only');
                        ?>
                        <div class="d-flex gap-3 flex-wrap">
                            <div class="form-check">
                                <input class="form-check-input" type="radio"
                                       name="export_mode" id="modConfirmed" value="confirmed_only"
                                       <?= $exportMode === 'confirmed_only' ? 'checked' : '' ?>
                                       <?= !$isConnected ? 'disabled' : '' ?>>
                                <label class="form-check-label" for="modConfirmed">
                                    <strong><?= __('gsheets.export_confirmed_only', 'Confirmed orders only') ?></strong>
                                    <span class="text-muted small d-block"><?= __('gsheets.export_confirmed_hint', 'Only export when an order is confirmed') ?></span>
                                </label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="radio"
                                       name="export_mode" id="modAll" value="all_orders"
                                       <?= $exportMode === 'all_orders' ? 'checked' : '' ?>
                                       <?= !$isConnected ? 'disabled' : '' ?>>
                                <label class="form-check-label" for="modAll">
                                    <strong><?= __('gsheets.export_all_orders', 'All orders (on receipt)') ?></strong>
                                    <span class="text-muted small d-block"><?= __('gsheets.export_all_hint', 'Export every new order immediately when received') ?></span>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- تفعيل + حفظ -->
                <div class="d-flex align-items-center justify-content-between flex-wrap gap-3 pt-3 border-top">
                    <div class="form-check form-switch mb-0">
                        <input class="form-check-input" type="checkbox" name="enabled"
                               id="gsheetsEnabled" value="1"
                               <?= $isEnabled ? 'checked' : '' ?>
                               <?= !$isConnected ? 'disabled' : '' ?>>
                        <label class="form-check-label fw-semibold" for="gsheetsEnabled">
                            <?= __('gsheets.enable_auto','Export confirmed orders automatically') ?>
                        </label>
                    </div>
                    <button type="submit" class="btn btn-primary px-4" <?= !$isConnected ? 'disabled' : '' ?>>
                        <i class="bi bi-save me-1"></i><?= __('gsheets.save_config','Save Configuration') ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- ══════════════════════════════════════════════
         أعمدة الـ Sheet
    ══════════════════════════════════════════════ -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white border-bottom py-3">
            <h6 class="mb-0 fw-semibold">
                <i class="bi bi-layout-three-columns me-2 text-muted"></i>
                <?= __('gsheets.columns_title','Sheet Columns (auto-added in this order)') ?>
            </h6>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th class="ps-3"><?= __('gsheets.col_letter','Column') ?></th>
                            <th><?= __('gsheets.col_name','Field') ?></th>
                            <th><?= __('gsheets.col_example','Example') ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $cols = [
                            ['A', __('gsheets.col_order_id','Order ID'),        '#1042'],
                            ['B', __('gsheets.col_date','Date'),                '2025-01-15 14:30'],
                            ['C', __('gsheets.col_product','Product'),          'Wireless Earbuds Pro'],
                            ['D', __('gsheets.col_qty','Quantity'),             '2'],
                            ['E', __('gsheets.col_size','Size'),                'XL'],
                            ['F', __('gsheets.col_color','Color'),              'Black'],
                            ['G', __('gsheets.col_name','Customer Name'),       'Ahmed Benali'],
                            ['H', __('gsheets.col_phone','Phone'),              '0555123456'],
                            ['I', __('gsheets.col_wilaya','Wilaya'),            '09'],
                            ['J', __('gsheets.col_commune','Commune'),          'Blida'],
                            ['K', __('gsheets.col_shipping_type','Delivery'),   'home'],
                            ['L', __('gsheets.col_shipping_price','Ship Price'),'600'],
                            ['M', __('gsheets.col_total','Total'),              '3200'],
                            ['N', __('gsheets.col_status','Status'),            'confirmed'],
                            ['O', __('gsheets.col_notes','Notes'),              ''],
                            ['P', __('gsheets.col_source','Source'),            'facebook'],
                            ['Q', __('gsheets.col_shipper','Shipper'),          'yalidine'],
                        ];
                        foreach ($cols as [$letter, $name, $example]): ?>
                        <tr>
                            <td class="ps-3">
                                <span class="badge bg-primary-subtle text-primary fw-bold"><?= $letter ?></span>
                            </td>
                            <td class="fw-semibold small"><?= $name ?></td>
                            <td class="text-muted small font-monospace"><?= htmlspecialchars($example) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>
</section>
</div>

<script>
function toggleSecret() {
    const inp  = document.getElementById('clientSecretInput');
    const icon = document.getElementById('secretEyeIcon');
    inp.type   = inp.type === 'password' ? 'text' : 'password';
    icon.className = inp.type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
}

async function loadFiles() {
    const btn = event.target.closest('button');
    const sel = document.getElementById('fileSelect');
    const origHtml = btn.innerHTML;

    btn.disabled = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>';

    try {
        const r = await fetch('/admin/settings/gsheets/files', { credentials: 'same-origin' });
        const d = await r.json();

        if (d.success && d.files?.length) {
            const current = sel.value;
            sel.innerHTML = '<option value=""><?= __('gsheets.select_file_placeholder','Select...') ?></option>';
            d.files.forEach(f => {
                const opt = document.createElement('option');
                opt.value = f.id; opt.textContent = f.name;
                if (f.id === current) opt.selected = true;
                sel.appendChild(opt);
            });
            if (current) loadSheets(current);
        } else {
            alert(d.error || '<?= __('gsheets.no_files','No spreadsheets found in your Drive') ?>');
        }
    } catch(e) {
        alert('<?= __('errors.network','Network error') ?>');
    } finally {
        btn.disabled = false;
        btn.innerHTML = origHtml;
    }
}

async function loadSheets(spreadsheetId) {
    if (!spreadsheetId) return;
    const sel = document.getElementById('sheetSelect');
    sel.innerHTML = '<option><?= __('gsheets.loading','Loading...') ?></option>';

    try {
        const r = await fetch('/admin/settings/gsheets/sheets?spreadsheet_id=' + encodeURIComponent(spreadsheetId), {
            credentials: 'same-origin'
        });
        const d = await r.json();
        const current = '<?= htmlspecialchars($sheetName) ?>';
        sel.innerHTML = '<option value=""><?= __('gsheets.select_sheet_placeholder','Select...') ?></option>';
        if (d.success && d.sheets?.length) {
            d.sheets.forEach(name => {
                const opt = document.createElement('option');
                opt.value = name; opt.textContent = name;
                if (name === current) opt.selected = true;
                sel.appendChild(opt);
            });
        }
    } catch(e) {
        sel.innerHTML = '<option value=""><?= __('gsheets.select_sheet_placeholder','Select...') ?></option>';
    }
}

<?php if ($isConnected && !empty($spreadsheetId)): ?>
document.addEventListener('DOMContentLoaded', () => loadFiles());
<?php endif; ?>
</script>