<?php
// File: admin/asana-accounts.php

require_once plugin_dir_path(__FILE__) . '/../includes/security.php';

function afb_render_asana_accounts_page() {
    global $wpdb;
    $table = $wpdb->prefix . 'asana_accounts';

    // Handle form submission (Add/Edit)
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && check_admin_referer('afb_save_account')) {
        $id            = isset($_POST['account_id']) ? intval($_POST['account_id']) : 0;
        $label         = sanitize_text_field($_POST['label']);
        $pat_raw       = sanitize_textarea_field($_POST['pat']);
        $portfolio_gid = sanitize_text_field($_POST['portfolio_gid']);

        $pat_encrypted = afb_encrypt($pat_raw);

        if ($id > 0) {
            $wpdb->update($table, [
                'label'         => $label,
                'pat'           => $pat_encrypted,
                'portfolio_gid' => $portfolio_gid,
            ], ['id' => $id]);
        } else {
            $wpdb->insert($table, [
                'label'         => $label,
                'pat'           => $pat_encrypted,
                'portfolio_gid' => $portfolio_gid,
                'created_at'    => current_time('mysql'),
                'active'        => 1,
            ]);
        }

        wp_redirect(admin_url('admin.php?page=asana-accounts'));
        exit;
    }

    // Handle delete
    if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
        check_admin_referer('afb_delete_account_' . $_GET['delete']);
        $wpdb->delete($table, ['id' => intval($_GET['delete'])]);
        wp_redirect(admin_url('admin.php?page=asana-accounts'));
        exit;
    }

    // ✅ Handle activate/deactivate
    if (isset($_GET['toggle_active']) && is_numeric($_GET['toggle_active'])) {
        $id = intval($_GET['toggle_active']);
        $current = $wpdb->get_var($wpdb->prepare("SELECT active FROM $table WHERE id = %d", $id));
        $new_status = ($current == 1) ? 0 : 1;
        $wpdb->update($table, ['active' => $new_status], ['id' => $id]);
        wp_redirect(admin_url('admin.php?page=asana-accounts'));
        exit;
    }

    // Get all accounts
    $accounts = $wpdb->get_results("SELECT * FROM $table ORDER BY id DESC", ARRAY_A);

    foreach ($accounts as &$acc) {
        $acc['pat_decrypted'] = afb_decrypt($acc['pat']);
    }
    unset($acc);

    // Editing?
    $editing = null;
    if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
        $editing = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE id = %d", $_GET['edit']), ARRAY_A);
        if ($editing) {
            $editing['pat'] = afb_decrypt($editing['pat']);
        }
    }
    ?>

    <div class="wrap">
        <h1 class="text-2xl mb-4">Asana Accounts</h1>

        <h2 class="text-xl mb-3"><?= $editing ? 'Edit Account' : 'Add New Account'; ?></h2>
        <form method="POST">
            <?php wp_nonce_field('afb_save_account'); ?>
            <input type="hidden" name="account_id" value="<?= esc_attr($editing['id'] ?? 0); ?>">

            <table class="form-table">
                <tr>
                    <th><label for="label">Account Label</label></th>
                    <td><input name="label" type="text" required class="regular-text" value="<?= esc_attr($editing['label'] ?? '') ?>"></td>
                </tr>
                <tr>
                    <th><label for="pat">Asana PAT</label></th>
                    <td>
                        <textarea name="pat" rows="3" class="large-text code" required><?= esc_textarea($editing['pat'] ?? '') ?></textarea>
                    </td>
                </tr>
                <tr>
                    <th><label for="portfolio_gid">Portfolio GID (optional)</label></th>
                    <td><input name="portfolio_gid" type="text" class="regular-text" value="<?= esc_attr($editing['portfolio_gid'] ?? '') ?>"></td>
                </tr>
            </table>

            <?php submit_button($editing ? 'Update Account' : 'Add Account'); ?>
        </form>

        <hr>

        <h2 class="mt-6 mb-2">Saved Accounts</h2>

        <?php if (empty($accounts)) : ?>
            <p>No accounts saved yet.</p>
        <?php else : ?>
            <table class="widefat striped">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Label</th>
                        <th>PAT (Truncated)</th>
                        <th>Portfolio GID</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($accounts as $acc): ?>
                    <tr>
                        <td><?= esc_html($acc['id']) ?></td>
                        <td><?= esc_html($acc['label']) ?></td>
                        <td><?= esc_html(substr($acc['pat_decrypted'], 0, 10)) ?>…</td>
                        <td><?= esc_html($acc['portfolio_gid'] ?: '—') ?></td>
                        <td>
                            <?php if ($acc['active']): ?>
                                <a href="<?= esc_url(admin_url("admin.php?page=asana-accounts&toggle_active={$acc['id']}")) ?>" class="text-green-600">🟢 Active</a>
                            <?php else: ?>
                                <a href="<?= esc_url(admin_url("admin.php?page=asana-accounts&toggle_active={$acc['id']}")) ?>" class="text-gray-500">⚪ Inactive</a>
                            <?php endif; ?>
                        </td>
                        <td>
                            <a href="<?= wp_nonce_url(admin_url('admin.php?page=asana-accounts&edit=' . $acc['id']), 'afb_save_account') ?>">Edit</a> |
                            <a href="<?= wp_nonce_url(admin_url('admin.php?page=asana-accounts&delete=' . $acc['id']), 'afb_delete_account_' . $acc['id']) ?>" onclick="return confirm('Delete this account?');">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
<?php
}
