<?php
require_once '../config.php';
requireLogin('admin');
require_once '../includes/api.php';

$message = '';
$message_type = 'success';
$test_result = null;

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'save_token') {
        $new_token = trim($_POST['sportmonks_token'] ?? '');
        $api_mode = $_POST['api_mode'] ?? 'auto';
        
        $settings = get_api_settings();
        $settings['sportmonks_token'] = $new_token;
        $settings['api_mode'] = $api_mode;
        
        if (save_api_settings($settings)) {
            $message = 'API settings updated successfully!';
            $message_type = 'success';
        } else {
            $message = 'Failed to save settings. Please check directory permissions.';
            $message_type = 'danger';
        }
    }
    
    if ($action === 'test_token') {
        $token_to_test = trim($_POST['test_token'] ?? get_active_token());
        $test_result = test_sportmonks_api($token_to_test);
        
        // Save test result
        $settings = get_api_settings();
        $settings['last_tested'] = date('Y-m-d H:i:s');
        $settings['last_status'] = $test_result['http_code'];
        $settings['last_message'] = $test_result['message'];
        save_api_settings($settings);
    }
}

$current_settings = get_api_settings();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SportMonks API Settings - Master Admin | Cricket Exchange</title>
    <link rel="stylesheet" href="../assets/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body>
<div class="dashboard-wrapper">
    <?php include 'partials/sidebar.php'; ?>

    <div class="main-content">
        <div class="topbar">
            <div class="topbar-title">
                <h1>SportMonks API Integration</h1>
                <p>Manage Cricket live scores API key and data source</p>
            </div>
            <div class="topbar-actions">
                <a href="../scores.php" target="_blank" class="btn btn-secondary btn-sm">
                    <i class="fas fa-external-link-alt"></i> View Live Scores
                </a>
            </div>
        </div>

        <div class="content-area">
            <?php if ($message): ?>
            <div class="alert alert-<?= $message_type ?>" style="margin-bottom:24px;">
                <i class="fas fa-<?= $message_type === 'success' ? 'check-circle' : 'exclamation-circle' ?>"></i>
                <?= htmlspecialchars($message) ?>
            </div>
            <?php endif; ?>

            <div style="display:grid; grid-template-columns: 1.2fr 1fr; gap:24px;">
                
                <!-- Token Configuration Card -->
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">
                            <span class="icon">🔑</span>
                            SportMonks API Configuration
                        </div>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="">
                            <input type="hidden" name="action" value="save_token">
                            
                            <div class="form-group" style="margin-bottom:20px;">
                                <label style="display:block; font-weight:700; margin-bottom:8px; font-size:13px; color:var(--text);">
                                    SportMonks API Token (v3)
                                </label>
                                <input type="text" name="sportmonks_token" class="form-control" 
                                       value="<?= htmlspecialchars($current_settings['sportmonks_token'] ?? '') ?>" 
                                       placeholder="Paste your SportMonks API token here..." required
                                       style="font-family:monospace; font-size:13px;">
                                <small style="display:block; color:var(--text-muted); margin-top:6px; font-size:12px;">
                                    Token can be found in your <a href="https://my.sportmonks.com" target="_blank" style="color:var(--primary);">SportMonks Dashboard</a> under API > Tokens.
                                </small>
                            </div>

                            <div class="form-group" style="margin-bottom:24px;">
                                <label style="display:block; font-weight:700; margin-bottom:8px; font-size:13px; color:var(--text);">
                                    Cricket Data Feed Mode
                                </label>
                                <select name="api_mode" class="form-control">
                                    <option value="auto" <?= ($current_settings['api_mode'] ?? '') === 'auto' ? 'selected' : '' ?>>
                                        Auto Fallback (Recommended: SportMonks API when available, seamless simulated matches if token inactive)
                                    </option>
                                    <option value="live_only" <?= ($current_settings['api_mode'] ?? '') === 'live_only' ? 'selected' : '' ?>>
                                        Live Only (Strictly SportMonks API - empty if API has no matches or error)
                                    </option>
                                    <option value="demo_only" <?= ($current_settings['api_mode'] ?? '') === 'demo_only' ? 'selected' : '' ?>>
                                        Simulated / Demo Matches Only
                                    </option>
                                </select>
                            </div>

                            <div style="display:flex; gap:12px;">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i> Save Settings
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- API Connection Test Card -->
                <div class="card">
                    <div class="card-header">
                        <div class="card-title">
                            <span class="icon">⚡</span>
                            Test API Connection
                        </div>
                    </div>
                    <div class="card-body">
                        <p style="color:var(--text-muted); font-size:13px; margin-bottom:18px;">
                            Test your token directly against the SportMonks v3 Cricket endpoint (<code style="color:var(--primary);">api.sportmonks.com/v3/cricket/fixtures</code>).
                        </p>

                        <form method="POST" action="">
                            <input type="hidden" name="action" value="test_token">
                            <input type="hidden" name="test_token" value="<?= htmlspecialchars($current_settings['sportmonks_token'] ?? '') ?>">
                            <button type="submit" class="btn btn-secondary btn-full" style="margin-bottom:20px;">
                                <i class="fas fa-plug"></i> Test Active Token Now
                            </button>
                        </form>

                        <?php if ($test_result): ?>
                        <div style="background:var(--bg-card2); border:1px solid var(--border); border-radius:12px; padding:16px; margin-top:16px;">
                            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
                                <span style="font-weight:700; font-size:13px;">Test Result:</span>
                                <?php if ($test_result['success']): ?>
                                <span style="background:rgba(0,212,170,0.15); color:var(--primary); font-size:11px; font-weight:800; padding:3px 10px; border-radius:20px;">● CONNECTED (200 OK)</span>
                                <?php else: ?>
                                <span style="background:rgba(255,77,109,0.15); color:#ff4d6d; font-size:11px; font-weight:800; padding:3px 10px; border-radius:20px;">● FAILED (HTTP <?= $test_result['http_code'] ?>)</span>
                                <?php endif; ?>
                            </div>
                            
                            <p style="font-size:13px; color:<?= $test_result['success'] ? 'var(--primary)' : '#ff4d6d' ?>; margin-bottom:12px; font-weight:600;">
                                <?= htmlspecialchars($test_result['message']) ?>
                            </p>

                            <?php if (!$test_result['success']): ?>
                            <div style="font-size:12px; color:var(--text-muted); line-height:1.6; border-top:1px solid var(--border); padding-top:10px;">
                                <strong>Troubleshooting Guide:</strong>
                                <ul style="margin:6px 0 0 16px; padding:0;">
                                    <li>Agar HTTP 401 aa raha hai: Token galat hai ya expire ho chuka hai. Naya token create karein.</li>
                                    <li>Agar HTTP 403 aa raha hai: Aapke account pe Cricket API plan active nahi hai.</li>
                                    <li>Site par live cricket simulated mode mein chalti rahegi jab tak sahi token nahi milta.</li>
                                </ul>
                            </div>
                            <?php endif; ?>

                            <?php if (!empty($test_result['raw_response'])): ?>
                            <details style="margin-top:12px;">
                                <summary style="font-size:11px; color:var(--text-dim); cursor:pointer;">Show Raw Response</summary>
                                <pre style="background:#0d111c; padding:10px; border-radius:8px; font-size:11px; color:#aaa; margin-top:6px; overflow-x:auto; max-height:150px;"><?= htmlspecialchars(substr($test_result['raw_response'], 0, 500)) ?></pre>
                            </details>
                            <?php endif; ?>
                        </div>
                        <?php elseif (!empty($current_settings['last_tested'])): ?>
                        <div style="font-size:12px; color:var(--text-muted); padding:10px; background:var(--bg-card2); border-radius:8px;">
                            <strong>Last Test:</strong> <?= htmlspecialchars($current_settings['last_tested']) ?><br>
                            <strong>Status:</strong> HTTP <?= htmlspecialchars($current_settings['last_status'] ?? '-') ?><br>
                            <strong>Note:</strong> <?= htmlspecialchars($current_settings['last_message'] ?? '-') ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

            </div>

            <!-- Endpoint Reference -->
            <div class="card" style="margin-top:24px;">
                <div class="card-header">
                    <div class="card-title">
                        <span class="icon">📖</span>
                        SportMonks v3 Cricket Integration Info
                    </div>
                </div>
                <div class="card-body">
                    <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap:16px; font-size:13px;">
                        <div style="background:var(--bg-card2); padding:16px; border-radius:12px; border:1px solid var(--border);">
                            <div style="font-weight:700; color:var(--primary); margin-bottom:6px;">Live In-Play Endpoint</div>
                            <code style="color:var(--text-muted); font-size:12px; word-break:break-all;">GET /v3/cricket/fixtures?filter[status]=live</code>
                            <p style="color:var(--text-dim); margin-top:6px; font-size:12px;">Refreshes every 15 seconds for real-time scores.</p>
                        </div>
                        <div style="background:var(--bg-card2); padding:16px; border-radius:12px; border:1px solid var(--border);">
                            <div style="font-weight:700; color:var(--primary); margin-bottom:6px;">Upcoming Fixtures</div>
                            <code style="color:var(--text-muted); font-size:12px; word-break:break-all;">GET /v3/cricket/fixtures?filter[starts_between]=today,next</code>
                            <p style="color:var(--text-dim); margin-top:6px; font-size:12px;">Cached for 2 minutes to conserve API quota.</p>
                        </div>
                        <div style="background:var(--bg-card2); padding:16px; border-radius:12px; border:1px solid var(--border);">
                            <div style="font-weight:700; color:var(--primary); margin-bottom:6px;">Match Scorecards</div>
                            <code style="color:var(--text-muted); font-size:12px; word-break:break-all;">GET /v3/cricket/fixtures/{id}?include=batting;bowling;runs</code>
                            <p style="color:var(--text-dim); margin-top:6px; font-size:12px;">Full ball and player statistics breakdown.</p>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
<?php include 'partials/scripts.php'; ?>
</body>
</html>
