const express = require('express');
const mysql = require('mysql2/promise');
const cors = require('cors');
const app = express();

// --- 1. إعدادات قاعدة البيانات ---
const dbConfig = {
    host: 'localhost',
    user: 'sitegeeky_app',
    password: 'appscoretank281243',
    database: 'sitegeeky_appscoretank',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
};

const pool = mysql.createPool(dbConfig);
const DB_PREFIX = 'wp47_';

app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// --- 2. التحقق من التوكن (نفس منطق النظام السابق) ---
async function isValidToken(req) {
    const token = req.query.token || req.body.token;
    const domain = req.query.domain || req.body.domain;

    if (!token || !domain) return false;

    try {
        const [rows] = await pool.execute('SELECT user_domain, expires_at FROM api_tokens WHERE token = ? LIMIT 1', [token]);
        if (rows.length > 0) {
            const dbDomain = rows[0].user_domain.replace(/^www\./, '').trim();
            let requestDomain = domain.replace(/^https?:\/\//, '').replace(/\/$/, '').replace(/^www\./, '').trim();
            if (dbDomain === requestDomain) {
                const expiresAt = new Date(rows[0].expires_at);
                if (expiresAt < new Date()) return 'expired';
                return true;
            }
        }
    } catch (error) { console.error("Token Error:", error); }
    return false;
}

const checkAuth = async (req, res, next) => {
    // استثناء SSE من الرد المباشر بـ JSON
    if (req.path.startsWith('/sse')) return next();
    
    const valid = await isValidToken(req);
    if (valid === true) next();
    else if (valid === 'expired') res.json({ success: false, message: 'الاشتراك منتهي.' });
    else res.status(403).json({ success: false, message: 'التوكن أو النطاق غير صالح.' });
};

// --- 3. نقاط النهاية (API Endpoints) ---

// أ) جلب قائمة كل البطولات
app.get('/leagues', checkAuth, async (req, res) => {
    try {
        const [rows] = await pool.query(`SELECT league_id, league_name, league_slug, league_url, league_logo FROM ${DB_PREFIX}leagues_list ORDER BY league_name ASC`);
        res.json({ success: true, data: rows });
    } catch (error) {
        console.error(error); res.status(500).json({ success: false, message: 'خطأ في الخادم' });
    }
});

// ب) جلب مباريات بطولة محددة (Fixtures)
app.get('/league/:id/fixtures', checkAuth, async (req, res) => {
    try {
        const leagueId = req.params.id;
        // جلب معلومات البطولة أولاً
        const [leagueInfo] = await pool.execute(`SELECT league_name FROM ${DB_PREFIX}leagues_list WHERE league_id = ?`, [leagueId]);
        if (leagueInfo.length === 0) return res.json({ success: false, message: 'البطولة غير موجودة' });

        // جلب الأسابيع والمباريات
        const [weeks] = await pool.execute(`SELECT week_name, matches_json, last_scraped FROM ${DB_PREFIX}league_fixture_weeks WHERE league_id = ? ORDER BY week_name`, [leagueId]);
        
        let fixturesByWeek = {};
        let lastUpdated = null;

        weeks.forEach(week => {
            fixturesByWeek[week.week_name] = JSON.parse(week.matches_json || '[]');
            // تحديد أحدث تاريخ تحديث
            const scrapedTime = new Date(week.last_scraped).getTime();
            if (!lastUpdated || scrapedTime > lastUpdated) lastUpdated = week.last_scraped;
        });

        res.json({
            success: true,
            data: {
                league_info: { id: leagueId, name: leagueInfo[0].league_name },
                fixtures_by_week: fixturesByWeek,
                last_updated: lastUpdated
            }
        });
    } catch (error) {
        console.error(error); res.status(500).json({ success: false, message: 'خطأ في جلب المباريات' });
    }
});

// ج) جلب الترتيب (Standings)
app.get('/league/:id/standings', checkAuth, async (req, res) => {
    try {
        const leagueId = req.params.id;
        const [rows] = await pool.execute(`
            SELECT l.league_name, s.standings_json, s.last_scraped 
            FROM ${DB_PREFIX}leagues_list l
            LEFT JOIN ${DB_PREFIX}league_standings s ON l.league_id = s.league_id
            WHERE l.league_id = ?`, [leagueId]);

        if (rows.length === 0) return res.json({ success: false, message: 'البطولة غير موجودة' });

        const result = rows[0];
        res.json({
            success: true,
            data: {
                league_info: { id: leagueId, name: result.league_name },
                standings: JSON.parse(result.standings_json || '[]'),
                last_updated: result.last_scraped
            }
        });
    } catch (error) { console.error(error); res.status(500).json({ success: false, message: 'خطأ في جلب الترتيب' }); }
});

// د) جلب الهدافين (Top Scorers)
app.get('/league/:id/scorers', checkAuth, async (req, res) => {
    try {
        const leagueId = req.params.id;
        const [rows] = await pool.execute(`
            SELECT l.league_name, t.top_scorers_json, t.last_scraped 
            FROM ${DB_PREFIX}leagues_list l
            LEFT JOIN ${DB_PREFIX}league_top_scorers t ON l.league_id = t.league_id
            WHERE l.league_id = ?`, [leagueId]);

        if (rows.length === 0) return res.json({ success: false, message: 'البطولة غير موجودة' });

        const result = rows[0];
        res.json({
            success: true,
            data: {
                league_info: { id: leagueId, name: result.league_name },
                top_scorers: JSON.parse(result.top_scorers_json || '[]'),
                last_updated: result.last_scraped
            }
        });
    } catch (error) { console.error(error); res.status(500).json({ success: false, message: 'خطأ في جلب الهدافين' }); }
});

// هـ) جلب الانتقالات (Transfers) - مع Pagination
app.get('/transfers', checkAuth, async (req, res) => {
    try {
        let page = parseInt(req.query.page) || 1;
        let limit = parseInt(req.query.limit) || 20;
        if (page < 1) page = 1;
        if (limit < 1) limit = 10;
        const offset = (page - 1) * limit;

        // حساب العدد الإجمالي
        const [countResult] = await pool.query(`SELECT COUNT(*) as total FROM ${DB_PREFIX}transfers`);
        const totalTransfers = countResult[0].total;
        const totalPages = Math.ceil(totalTransfers / limit);

        // جلب البيانات
        const [transfers] = await pool.query(`
            SELECT transfer_id, transfer_date, player_name, player_image_url, 
                   from_team_name, from_team_image_url, to_team_name, to_team_image_url, transfer_details
            FROM ${DB_PREFIX}transfers
            ORDER BY transfer_date DESC, transfer_id DESC
            LIMIT ? OFFSET ?
        `, [limit, offset]);

        res.json({
            success: true,
            data: {
                pagination: { current_page: page, per_page: limit, total_pages: totalPages, total_transfers: totalTransfers },
                transfers: transfers
            }
        });
    } catch (error) { console.error(error); res.status(500).json({ success: false, message: 'خطأ في جلب الانتقالات' }); }
});

// --- 4. SSE (التحديث اللحظي) ---

// أ) SSE للبطولات (يراقب الترتيب والهدافين)
app.get('/sse/league/:id', async (req, res) => {
    // 1. تحقق التوكن
    const valid = await isValidToken(req);
    if (valid !== true) { res.write(`data: ${JSON.stringify({ error: 'Unauthorized' })}\n\n`); return res.end(); }

    const leagueId = req.params.id;
    
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('Access-Control-Allow-Origin', '*');

    let lastStandingsUpdate = '1970-01-01 00:00:00';
    let lastScorersUpdate = '1970-01-01 00:00:00';

    const checkForUpdates = async () => {
        try {
            // فحص الترتيب
            const [standings] = await pool.execute(`
                SELECT standings_json, last_scraped FROM ${DB_PREFIX}league_standings 
                WHERE league_id = ? AND last_scraped > ?`, [leagueId, lastStandingsUpdate]);
            
            if (standings.length > 0) {
                lastStandingsUpdate = standings[0].last_scraped;
                res.write(`event: standings_update\n`);
                res.write(`data: ${JSON.stringify({ league_id: leagueId, standings: JSON.parse(standings[0].standings_json) })}\n\n`);
            }

            // فحص الهدافين
            const [scorers] = await pool.execute(`
                SELECT top_scorers_json, last_scraped FROM ${DB_PREFIX}league_top_scorers 
                WHERE league_id = ? AND last_scraped > ?`, [leagueId, lastScorersUpdate]);

            if (scorers.length > 0) {
                lastScorersUpdate = scorers[0].last_scraped;
                res.write(`event: scorers_update\n`);
                res.write(`data: ${JSON.stringify({ league_id: leagueId, top_scorers: JSON.parse(scorers[0].top_scorers_json) })}\n\n`);
            }

            // Ping
            res.write(`: keep-alive\n\n`);

        } catch (err) { console.error("SSE League Error:", err); }
    };

    const interval = setInterval(checkForUpdates, 10000); // كل 10 ثواني (بيانات البطولات تتحدث ببطء)
    req.on('close', () => clearInterval(interval));
});

// ب) SSE للانتقالات (يراقب الانتقالات الجديدة)
app.get('/sse/transfers', async (req, res) => {
    const valid = await isValidToken(req);
    if (valid !== true) { res.write(`data: ${JSON.stringify({ error: 'Unauthorized' })}\n\n`); return res.end(); }

    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');
    res.setHeader('Access-Control-Allow-Origin', '*');

    // تحديد آخر ID عند بدء الاتصال (لتجنب إرسال القديم)
    let lastTransferId = 0;
    try {
        const [rows] = await pool.query(`SELECT MAX(transfer_id) as max_id FROM ${DB_PREFIX}transfers`);
        lastTransferId = rows[0].max_id || 0;
    } catch(e) {}

    const checkForTransfers = async () => {
        try {
            const [newTransfers] = await pool.execute(`
                SELECT * FROM ${DB_PREFIX}transfers 
                WHERE transfer_id > ? ORDER BY transfer_id ASC`, [lastTransferId]);

            if (newTransfers.length > 0) {
                // تحديث آخر ID
                lastTransferId = newTransfers[newTransfers.length - 1].transfer_id;
                
                res.write(`event: new_transfers\n`);
                res.write(`data: ${JSON.stringify(newTransfers)}\n\n`);
            } else {
                res.write(`: keep-alive\n\n`);
            }
        } catch (err) { console.error("SSE Transfers Error:", err); }
    };

    const interval = setInterval(checkForTransfers, 15000); // كل 15 ثانية
    req.on('close', () => clearInterval(interval));
});

// تشغيل السيرفر على المنفذ 3002
const PORT = process.env.PORT || 3002;
app.listen(PORT, () => {
    console.log(`Leagues API Server running on port ${PORT}`);
});