// Import necessary modules
const express = require('express');
const cors = require('cors');
const admin = require('firebase-admin');
const mysql = require('mysql');
const dotenv = require('dotenv');
const assert = require('assert');
// const db = require('./config');

// Load environment variables from .env file
dotenv.config();

// Firebase Admin SDK configuration
const serviceAccount = require('./config/serviceAccountKey.json'); // Update with your serviceAccountKey.json file
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

// MySQL database connection setup
const db = mysql.createConnection({
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE,
    port: process.env.MYSQL_PORT,
});
  
// const db = mysql.createConnection({
//     host: "localhost",
//     user: "root",
//     password: "",
//     database:"iskalnik_dztps"
// });
  
db.connect((err) => {
    if (err) {
        console.error('MySQL connection failed:', err);
    } else {
        console.log('Connected to MySQL database');
    }
});

// Helper function to promisify database queries
const query = (sql, params) => {
    return new Promise((resolve, reject) => {
        db.query(sql, params, (err, result) => {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
    });
};
  

// Express application
const app = express();

// Middleware
app.use(cors());
app.use(express.json());

// Firebase authentication middleware
const authenticateFirebaseToken = async (req, res, next) => {
    try {
        const { authorization } = req.headers;
        if (!authorization || !authorization.startsWith('Bearer ')) {
            return res.status(401).json({ message: 'Unauthorized' });
        }

        const idToken = authorization.split('Bearer ')[1];
        const decodedToken = await admin.auth().verifyIdToken(idToken);
        req.uid = decodedToken.uid;
        next();
    } catch (error) {
        console.error('Error authenticating Firebase token:', error);
        return res.status(401).json({ message: 'Unauthorized' });
    }
};

// Protected route example
app.get('/express', authenticateFirebaseToken, (req, res) => {
    // Access user ID from req.uid
    // Fetch data from MySQL using the user ID or perform other operations
    res.json({ message: 'Protected route accessed successfully' });
});

// Start the Express server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});


/**********************************
 * clan
 *********************************/

function formClanStruct(from, id=null) {
    if (!id) id = from.id;
    return {
        'id': id,
        'id_izkaznica': from.id_izkaznica || "",
        'ime': from.ime || "",
        'priimek': from.priimek || "",
        'spol': from.spol || "",
        'datum_rojstva': from.datum_rojstva || "",
        'kraj_rojstva': from.kraj_rojstva || "",
        'drzavljanstvo': from.drzavljanstvo || "",
        'solska_izobrazba': from.solska_izobrazba || "",
        'telefondoma': from.telefondoma || "",
        'telefonsluzba': from.telefonsluzba || "",
        'telefonmobi': from.telefonmobi || "",
        'email': from.email || "",
        'spletnastran': from.spletnastran || "",
        'naslovbivalisca': from.naslovbivalisca || "",
        'ulica': from.ulica || "",
        'postna_stevilka': from.postna_stevilka || "",
        'posta': from.posta || "",
        'osnovni_poklic': from.osnovni_poklic || "",
        'sedanja_zaposlitev': from.sedanja_zaposlitev || "",
        'prevajalska_praksa': from.prevajalska_praksa || "",
        'nacin_pridobivanja_znanja_tujih_jezikov': from.nacin_pridobivanja_znanja_tujih_jezikov || "",
        'datum_vclanitve': from.datum_vclanitve || "",
        'materni_jezik': from.materni_jezik || "",
        'objava_v_iskalniku': from.objava_v_iskalniku || 0
    }
}

function formClanValueArray(res) {
    const body = res.body;
    return [body.id_izkaznica, body.ime, body.priimek, body.spol, body.datum_rojstva ? new Date(body.datum_rojstva) : null,
        body.kraj_rojstva, body.drzavljanstvo, body.solska_izobrazba, body.telefondoma,
        body.telefonsluzba, body.telefonmobi, body.email, body.spletnastran, body.naslovbivalisca,
        body.ulica, body.postna_stevilka, body.posta, body.osnovni_poklic, body.sedanja_zaposlitev, body.prevajalska_praksa, body.nacin_pridobivanja_znanja_tujih_jezikov, body.datum_vclanitve ? new Date(body.datum_vclanitve) : null,
        body.materni_jezik, body.objava_v_iskalniku
    ];
}

app.get("/express/api/v1/clan/", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT * 
    FROM clan`, (err, result, fields) => {
        if (err) {
            res.sendStatus(500);
            return;
        }
        const out = result.map(row => formClanStruct(row));
        res.status(200).json(out);
    });
});

app.get("/express/api/v1/clan/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT *
    FROM clan
    WHERE id = ?`, [req.params.id], (err, result, fields) => {
        if (result.length === 0 || err) {
            res.sendStatus(404);
            return;
        }
        const first = result[0];
        const out = formClanStruct(first);
        res.status(200).json(out);
    });
});

app.post("/express/api/v1/clan/", authenticateFirebaseToken, (req, res) => {
    db.query(`INSERT INTO clan (
        id_izkaznica, ime, priimek, spol, datum_rojstva, kraj_rojstva,
        drzavljanstvo, solska_izobrazba, telefondoma, telefonsluzba,
        telefonmobi, email, spletnastran, naslovbivalisca, ulica,
        postna_stevilka, posta, osnovni_poklic, sedanja_zaposlitev, prevajalska_praksa, nacin_pridobivanja_znanja_tujih_jezikov, datum_vclanitve,
        materni_jezik, objava_v_iskalniku
    )
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `, formClanValueArray(req), (err, result) => {
        if (!err && result.affectedRows === 1) {
            res.status(200).json(formClanStruct(req.body, result.insertId));
        } else {
            res.status(200).json(err);
            // res.sendStatus(400);
        }
    });
});

app.put("/express/api/v1/clan/:id", authenticateFirebaseToken, (req, res) => {
    const valueArr = formClanValueArray(req);
    valueArr.push(req.params.id);
    db.query(`UPDATE clan
    SET id_izkaznica=?, ime=?, priimek=?, spol=?, datum_rojstva=?, kraj_rojstva=?,
        drzavljanstvo=?, solska_izobrazba=?, telefondoma=?, telefonsluzba=?,
        telefonmobi=?, email=?, spletnastran=?, naslovbivalisca=?, ulica=?,
        postna_stevilka=?, posta=?, osnovni_poklic=?, sedanja_zaposlitev=?, prevajalska_praksa=?, nacin_pridobivanja_znanja_tujih_jezikov=?, datum_vclanitve=?,
        materni_jezik=?, objava_v_iskalniku=?
        WHERE id=?
    `, valueArr, (err, result, fields) => {
        if (!err && result.affectedRows === 1) {
            res.status(200).json(formClanStruct(req.body, req.params.id));
        } else {
            res.sendStatus(400);
        }
    });
});

app.delete("/express/api/v1/clan/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`DELETE FROM clan
    WHERE id = ?`, [req.params.id], (err, result, fields) => {
        if (!err && result.affectedRows === 1) {
            res.sendStatus(200);
        } else {
            res.sendStatus(400);
        }
    });
});

/**********************************
 * prevod
 *********************************/

function getVloge(prevodID) {
    return new Promise((resolve) => {
        db.query(`SELECT v.id as 'id', vloga, izpis_zenska, izpis_moski
              FROM prevod_vloga as pv
              JOIN vloga as v
              ON pv.vloga_id = v.id
              WHERE pv.prevod_id = ?
        `, [prevodID], (err, result, fields) => {
            if (err) throw err;
            function formVloga(row) {
                return {
                    'id': row.id,
                    'vloga': row.vloga,
                    'izpis_zenska': row.izpis_zenska,
                    'izpis_moski': row.izpis_moski
                }
            }
            resolve(result.map(row => formVloga(row)));
        });
    });


}
function getPodrocja(prevodID) {
    return new Promise((resolve) => {
        db.query(`SELECT p.id as 'id', podrocje
              FROM prevod_podrocje as pp
              JOIN podrocje as p
              ON pp.podrocje_id = p.id
              WHERE pp.prevod_id = ?
    `, [prevodID], (err, result, fields) => {
            if (err) throw err;
            function formPodrocje(row) {
                return {
                    'id': row.id,
                    'podrocje': row.podrocje,
                }
            }

            resolve(result.map(row => formPodrocje(row)));
        });
    });

}

async function formPrevodStruct(from, id=null) {
    if (!id) id = from.id;
    const out = {
        'id': id,
        'id_clan': from.id_clan,
        'rang': from.rang,
        'iz': from.iz,
        'v': from.v,
        'licenca_DZTPS': from.licenca_DZTPS,
    };
    const podrocja = await getPodrocja(id);
    const vloge = await getVloge(id);
    out.podrocja = podrocja;
    out.vloge = vloge;
    return out;
}
app.get("/express/api/v1/clan/:id/prevod/", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT p.id as 'id', id_clan, rang, iz.jezik as 'iz', v.jezik as 'v', licenca_DZTPS
              FROM prevod as p
              JOIN jezik as iz
              ON p.iz_id = iz.id
              JOIN jezik as v
              ON p.v_id = v.id
              WHERE id_clan = ?
    `, [req.params.id], async (err, result, fields) => {
        if (err) {
            res.sendStatus(500);
            return;
        }
        const out = await Promise.all(result.map(row => formPrevodStruct(row)));
        res.status(200).json(out);
    });
});

app.get("/express/api/v1/clan/:id/prevod/:pid", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT p.id as 'id', id_clan, rang, iz.jezik as 'iz', v.jezik as 'v', licenca_DZTPS
              FROM prevod as p
              JOIN jezik as iz
              ON p.iz_id = iz.id
              JOIN jezik as v
              ON p.v_id = v.id
              WHERE p.id_clan = ? AND p.id = ?
    `, [req.params.id, req.params.pid], async (err, result, fields) => {
        if (err || result.length === 0) {
            res.sendStatus(404);
            return;
        }
        const first = result[0];
        const out = await formPrevodStruct(first);
        res.status(200).json(out);
    });
});

async function addPrevodVloga(prevodID, vloga) {
    await query(`INSERT INTO prevod_vloga
(prevod_id, vloga_id) 
VALUES 
(?, (
    SELECT v.id
    FROM vloga as v
    WHERE v.vloga = ?
))
`, [prevodID, vloga]);
}
async function removePrevodVloga(prevodID, vloga) {
    await query(`DELETE FROM prevod_vloga
WHERE prevod_id=? AND vloga_id=(
    SELECT v.id
    FROM vloga as v
    WHERE v.vloga = ?
    ) 
`, [prevodID, vloga]);
}

async function addPrevodPodrocje(prevodID, podrocje) {
    await query(`INSERT INTO prevod_podrocje
(prevod_id, podrocje_id) 
VALUES 
(?, (
    SELECT p.id
    FROM podrocje as p
    WHERE p.podrocje=?
    ))
`, [prevodID, podrocje]);
}

async function removePrevodPodrocje(prevodID, podrocje) {
    await query(`DELETE FROM prevod_podrocje
WHERE prevod_id=? AND podrocje_id=(
    SELECT p.id
    FROM podrocje as p
    WHERE p.podrocje = ?
    )
`, [prevodID, podrocje]);
}

app.post("/express/api/v1/clan/:id/prevod/", async (req, res) => {
    await db.beginTransaction();
    try {
        assert(req.body.id_clan == req.params.id);
        const prevod = await query(`INSERT INTO prevod
(id_clan, rang, iz_id, v_id, licenca_DZTPS)
VALUES
(?, ?, (
    SELECT iz.id
    FROM jezik as iz
    WHERE iz.jezik=?
), (
    SELECT v.id
    FROM jezik as v
    WHERE v.jezik=?
    ), ?)   
`, [req.body.id_clan, req.body.rang, req.body.iz, req.body.v, req.body.licenca_DZTPS]);

        const prevodID = prevod.insertId;
        for (let podrocje of req.body.podrocja) {
            await addPrevodPodrocje(prevodID, podrocje.podrocje);
        }
        for (let vloga of req.body.vloge) {
            await addPrevodVloga(prevodID, vloga.vloga);
        }

        await db.commit();
        res.status(200).json(await formPrevodStruct(req.body, prevodID));
    } catch (e) {
        db.rollback();
        res.sendStatus(400);
    }
});

app.put("/express/api/v1/clan/:id/prevod/:pid", async (req, res) => {
    await db.beginTransaction();
    try {
        await query(`UPDATE prevod
                          SET id_clan=?,
                              rang=?,
                              iz_id=(SELECT iz.id
                                     FROM jezik as iz
                                     WHERE iz.jezik = ?),
                              v_id=(SELECT v.id
                                    FROM jezik as v
                                    WHERE v.jezik = ?),
                              licenca_DZTPS=?
                          WHERE id_clan=? AND id=?
        `, [req.body.id_clan, req.body.rang, req.body.iz, req.body.v, req.body.licenca_DZTPS, req.params.id, req.params.pid]);

        const prevod = await formPrevodStruct(req.body);

        // Synchronize podrocja
        const oldPodrocja = prevod.podrocja;
        const newPodrocja = req.body.podrocja;
        for (let podrocje of oldPodrocja) {
            // Podrocje not present in new -> delete
            if (!newPodrocja.some(p => p.id === podrocje.id))
                await removePrevodPodrocje(prevod.id, podrocje.podrocje);
        }
        for (let podrocje of newPodrocja) {
            // Podrocje present in new but not in old -> add
            if (!oldPodrocja.some(p => p.id === podrocje.id))
                await addPrevodPodrocje(prevod.id, podrocje.podrocje);
        }
        // Synchronize vloge
        const oldVloge = prevod.vloge;
        const newVloge = req.body.vloge;
        for (let vloga of oldVloge) {
            // Vloga not present in new -> delete
            if (!newVloge.some(v => v.id === vloga.id))
                await removePrevodVloga(prevod.id, vloga.vloga);
        }
        for (let vloga of newVloge) {
            // Vloga present in new but not in old -> add
            if (!oldVloge.some(v => v.id === vloga.id))
                await addPrevodVloga(prevod.id, vloga.vloga);
        }

        await db.commit();
        res.status(200).json(await formPrevodStruct(req.body));
    } catch (e) {
        db.rollback();
        res.sendStatus(400);
    }
});

app.delete("/express/api/v1/clan/:id/prevod/:pid", async (req, res) => {
    await db.beginTransaction();
    try {
        await query(`DELETE FROM prevod_podrocje WHERE prevod_id=?`, [req.params.pid]);
        await query(`DELETE FROM prevod_vloga WHERE prevod_id=?`, [req.params.pid]);
        await query(`DELETE FROM prevod WHERE id_clan=? AND id=?`, [req.params.id, req.params.pid]);
        await db.commit();
        res.sendStatus(200);
    } catch (e) {
        db.rollback();
        res.sendStatus(400);
    }
});

/**********************************
 * jezik
 *********************************/

function formJezikStruct(from, id=null) {
    if (!id) id = from.id;
    return {
        'id': id,
        'jezik': from.jezik
    };
}

app.get("/express/api/v1/jezik/", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT id, jezik
    FROM jezik`, (err, result, fields) => {
       if (err) {
           res.sendStatus(500);
           return;
       }
       const out = result.map(row => formJezikStruct(row));
       res.status(200).json(out);
    });
});

app.get("/express/api/v1/jezik/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT id, jezik
    FROM jezik
    WHERE id = ?`, [req.params.id], (err, result, fields) => {
        if (result.length === 0 || err) {
            res.sendStatus(404);
            return;
        }
        const first = result[0];
        const out = formJezikStruct(first);
        res.status(200).json(out);
    });
});

app.post("/express/api/v1/jezik/", authenticateFirebaseToken, (req, res) => {
    db.query(`INSERT INTO jezik
    (jezik)
    VALUES (?)`, [req.body.jezik], (err, result) => {
        if (!err && result.affectedRows === 1) {
            res.status(200).json(formJezikStruct(req.body, result.insertId));
        } else {
            res.sendStatus(400);
        }
    });
});

app.put("/express/api/v1/jezik/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`UPDATE jezik
    SET jezik = ?
    WHERE id = ?`, [req.body.jezik, req.params.id], (err, result) => {
        if (!err && result.affectedRows === 1) {
            res.status(200).json(formJezikStruct(req.body, req.params.id));
        } else {
            res.sendStatus(400);
        }
    });
});

app.delete("/express/api/v1/jezik/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`DELETE FROM jezik
    WHERE id = ?`, [req.params.id], (err, result, fields) => {
        if (!err && result.affectedRows === 1) {
            res.sendStatus(200);
        } else {
            res.sendStatus(400);
        }
    });
});

/**********************************
 * vloga
 *********************************/

function formVlogaStruct(from, id=null) {
    if (!id) id = from.id;
    return {
        'id': id,
        'vloga': from.vloga,
        'izpis_zenska': from.izpis_zenska,
        'izpis_moski': from.izpis_moski
    };
}

app.get("/express/api/v1/vloga/", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT id, vloga, izpis_zenska, izpis_moski
    FROM vloga`, (err, result, fields) => {
        if (err) {
            res.sendStatus(500);
            return;
        }
        const out = result.map(row => formVlogaStruct(row));
        res.status(200).json(out);
    });
});

app.get("/express/api/v1/vloga/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT id, vloga, izpis_zenska, izpis_moski
    FROM vloga
    WHERE id = ?`, [req.params.id], (err, result, fields) => {
        if (result.length === 0 || err) {
            res.sendStatus(404);
            return;
        }
        const first = result[0];
        const out = formVlogaStruct(first);
        res.status(200).json(out);
    });
});

app.post("/express/api/v1/vloga/", authenticateFirebaseToken, (req, res) => {
    db.query(`INSERT INTO vloga
    (vloga, izpis_zenska, izpis_moski)
    VALUES (?, ?, ?)`, [req.body.vloga, req.body.izpis_zenska, req.body.izpis_moski], (err, result) => {
        if (!err && result.affectedRows === 1) {
            res.status(200).json(formVlogaStruct(req.body, result.insertId));
        } else {
            res.sendStatus(400);
        }
    });
});

app.put("/express/api/v1/vloga/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`UPDATE vloga
    SET vloga = ?, izpis_zenska = ?, izpis_moski = ?
    WHERE id = ?`, [req.body.vloga, req.body.izpis_zenska, req.body.izpis_moski, req.params.id], (err, result) => {
        if (!err && result.affectedRows === 1) {
            res.status(200).json(formVlogaStruct(req.body, req.params.id));
        } else {
            res.sendStatus(400);
        }
    });
});

app.delete("/express/api/v1/vloga/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`DELETE FROM vloga
    WHERE id = ?`, [req.params.id], (err, result, fields) => {
        if (!err && result.affectedRows === 1) {
            res.sendStatus(200);
        } else {
            res.sendStatus(400);
        }
    });
});

/**********************************
 * podrocje
 *********************************/

function formPodrocjeStruct(from, id=null) {
    if (!id) id = from.id;
    return {
        'id': id,
        'podrocje': from.podrocje,
    };
}

app.get("/express/api/v1/podrocje", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT id, podrocje
    FROM podrocje`, (err, result, fields) => {
        if (err) {
            res.sendStatus(500);
            return;
        }
        const out = result.map(row => formPodrocjeStruct(row));
        res.status(200).json(out);
    });
});

app.get("/express/api/v1/podrocje/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`SELECT id, podrocje
    FROM podrocje
    WHERE id = ?`, [req.params.id], (err, result, fields) => {
        if (result.length === 0 || err) {
            res.sendStatus(404);
            return;
        }
        const first = result[0];
        const out = formPodrocjeStruct(first);
        res.status(200).json(out);
    });
});

app.post("/express/api/v1/podrocje/", authenticateFirebaseToken, (req, res) => {
    db.query(`INSERT INTO podrocje
    (podrocje)
    VALUES (?)`, [req.body.podrocje], (err, result) => {
        if (!err && result.affectedRows === 1) {
            res.status(200).json(formPodrocjeStruct(req.body, result.insertId));
        } else {
            res.sendStatus(400);
        }
    });
});

app.put("/express/api/v1/podrocje/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`UPDATE podrocje
    SET podrocje = ?
    WHERE id = ?`, [req.body.podrocje, req.params.id], (err, result, fields) => {
        if (!err && result.affectedRows === 1) {
            res.status(200).json(formPodrocjeStruct(req.body, req.params.id));
        } else {
            res.sendStatus(400);
        }
    });
});

app.delete("/express/api/v1/podrocje/:id", authenticateFirebaseToken, (req, res) => {
    db.query(`DELETE FROM podrocje
    WHERE id = ?`, [req.params.id], (err, result, fields) => {
        if (!err && result.affectedRows === 1) {
            res.sendStatus(200);
        } else {
            res.sendStatus(400);
        }
    });

});


// ISKALNIK

app.get('/express_backend', (req, res) => {
    res.send({ express: `YOUR BACKEND IS CONNECTED` });
});

app.post('/express_backend/api/v1/iskanje', (req,res) => {
    const iskanjeIme = req.body.iskanjeNiz;
    const iskanjeCrka = req.body.iskanjeCrkaPriimek;
    const iskanjeIz = req.body.iskanjeIzvirniJezik;
    const iskanjeV = req.body.iskanjeCiljniJezik;
    const iskanjeRangi = req.body.iskanjeRang;
    const iskanjePodrocja = new Set(req.body.iskanjeStrokovnoPodrocje);
    const iskanjeVloge = new Set(req.body.iskanjeVloga);
    const iskanjeLicenca = req.body.iskanjeLicenca;

    // Build query
    const params = [];
    const queryConditions = [];
    if (iskanjeIme) {
        queryConditions.push("(LOWER(CONCAT(c.ime, ' ', c.priimek)) LIKE LOWER(?))");
        params.push(`%${iskanjeIme}%`);
    }
    if (iskanjeCrka) {
        queryConditions.push("(c.priimek LIKE (?))");
        params.push(`${iskanjeCrka}%`);
    }
    if (iskanjeIz) {
        queryConditions.push("(iz.jezik = (?))");
        params.push(iskanjeIz);
    }
    if (iskanjeV) {
        queryConditions.push("(v.jezik = (?))");
        params.push(iskanjeV);
    }
    const generateQuestionMarks = (n) => Array.from({ length: n }, () => '?').join(',');
    if (iskanjeRangi) {
        queryConditions.push(`(p.rang IN (${generateQuestionMarks(iskanjeRangi.length)}))`);
        params.push(...iskanjeRangi);
    }

    if (iskanjeLicenca) {
        queryConditions.push("(p.licenca_DZTPS = ?)")
        params.push(iskanjeLicenca)
    }


    db.query(`SELECT c.id as 'id' , c.ime as 'ime', c.priimek as 'priimek', c.spol as 'spol', c.telefondoma as 'telefondoma', c.telefonsluzba as 'telefonsluzba',
       c.telefonmobi as 'telefonmobi', c.email as 'email', c.spletnastran as 'spletnastran',
       p.rang as 'rang', iz.jezik as iz, v.jezik as v, p.licenca_DZTPS as 'licenca',
       (
           SELECT GROUP_CONCAT(po.podrocje SEPARATOR ';')
           FROM prevod_podrocje as pp
           JOIN podrocje as po
           ON pp.podrocje_id = po.id
           WHERE pp.prevod_id = p.id
           GROUP BY pp.prevod_id
       ) as 'podrocja',
       (
           SELECT GROUP_CONCAT(vl.vloga SEPARATOR ';')
           FROM prevod_vloga as pv
           JOIN vloga as vl
           ON pv.vloga_id = vl.id
           WHERE pv.prevod_id = p.id
           GROUP BY pv.prevod_id
       ) as 'vloge'
FROM clan as c
JOIN prevod as p
ON c.id = p.id_clan
JOIN jezik as iz
ON p.iz_id = iz.id
JOIN jezik as v
ON p.v_id = v.id
WHERE c.objava_v_iskalniku = 1
WHERE ${queryConditions.length ? queryConditions.join("AND") : "1=1"}`,
        params, (err, rows, fields)=> {
            if (err) throw err;
            if (rows.length == 0) {
                res.send({});
                return;
            }

            let out = [];
            for (let row of rows) {
                if (out.length <= 0 || out[out.length - 1].id !== row.id) {
                    out.push({
                        "id": row.id,
                        "ime": row.ime,
                        "priimek": row.priimek,
                        "spol": row.spol,
                        "telefondoma": row.telefondoma,
                        "telefonmobi": row.telefonmobi,
                        "telefonsluzba": row.telefonsluzba,
                        "email": row.email,
                        "spletnastran": row.spletnastran,
                        "prevodi": [],
                    });
                }
                let podrocja = row.podrocja?.split(';') || [];
                let vloge = row.vloge?.split(';') || [];
                if (iskanjePodrocja.size) {
                    podrocja = podrocja.filter((el) => iskanjePodrocja.has(el));
                    if (podrocja.length === 0) continue;
                }
                if (iskanjeVloge.size) {
                    vloge = vloge.filter((el) => iskanjeVloge.has(el));
                    if (vloge.length === 0) continue;
                }


                out[out.length - 1].prevodi.push({
                    "rang": row.rang,
                    "iz": row.iz,
                    "v": row.v,
                    "strokovnopodrocje": row.podrocja?.split(';'),
                    "vloga": row.vloge?.split(';'),
                });
            }
            out = out.filter((row) => row.prevodi.length > 0);
            res.send(JSON.stringify(out, null, 4));
        });

});

app.get("/express_backend/api/get/user/:user_id", (req, res) => {
    db.query(`SELECT c.id as 'id' , c.ime as 'ime', c.priimek as 'priimek', c.spol as 'spol', c.telefondoma as 'telefondoma', c.telefonsluzba as 'telefonsluzba',
       c.telefonmobi as 'telefonmobi', c.email as 'email', c.spletnastran as 'spletnastran',
       p.rang as 'rang', iz.jezik as iz, v.jezik as v,
       (
           SELECT GROUP_CONCAT(po.podrocje SEPARATOR ';')
           FROM prevod_podrocje as pp
           JOIN podrocje as po
           ON pp.podrocje_id = po.id
           WHERE pp.prevod_id = p.id
           GROUP BY pp.prevod_id
       ) as 'podrocja',
       (
           SELECT GROUP_CONCAT(vl.vloga SEPARATOR ';')
           FROM prevod_vloga as pv
           JOIN vloga as vl
           ON pv.vloga_id = vl.id
           WHERE pv.prevod_id = p.id
           GROUP BY pv.prevod_id
       ) as 'vloge'
FROM clan as c
JOIN prevod as p
ON c.id = p.id_clan
JOIN jezik as iz
ON p.iz_id = iz.id
JOIN jezik as v
ON p.v_id = v.id
WHERE c.id = ?
WHERE c.objava_v_iskalniku = 1
ORDER BY rang;`, [req.params.user_id], (err, rows, fields)=> {
        if (err) throw err;
        if (rows.length === 0) {
            res.send({});
            return;
        }

        const first = rows[0];

        let out = {
            "id": first.id,
            "ime": first.ime,
            "priimek": first.priimek,
            "telefondoma": first.telefondoma,
            "telefonmobi": first.telefonmobi,
            "telefonsluzba": first.telefonsluzba,
            "email": first.email,
            "spletnastran": first.spletnastran,
            "prevodi": [],
        };
        for (let row of rows) {
            out.prevodi.push({
                "id": row.id_prevod,
                "rang": row.rang,
                "iz": row.iz,
                "v": row.v,
                "strokovnopodrocje": row.podrocja?.split(';'),
                "vloga": row.vloge?.split(';'),
            });
        }
        res.send(JSON.stringify(out, null, 4));
    });

});

app.get("/express_backend/api/getAll", (req, res) => {
    db.query(`SELECT c.id as 'id' , c.ime as 'ime', c.priimek as 'priimek', c.spol as 'spol', c.telefondoma as 'telefondoma', c.telefonsluzba as 'telefonsluzba',
       c.telefonmobi as 'telefonmobi', c.email as 'email', c.spletnastran as 'spletnastran',
       p.rang as 'rang', iz.jezik as iz, v.jezik as v,
       (
           SELECT GROUP_CONCAT(po.podrocje SEPARATOR ';')
           FROM prevod_podrocje as pp
           JOIN podrocje as po
           ON pp.podrocje_id = po.id
           WHERE pp.prevod_id = p.id
           GROUP BY pp.prevod_id
       ) as 'podrocja',
       (
           SELECT GROUP_CONCAT(vl.vloga SEPARATOR ';')
           FROM prevod_vloga as pv
           JOIN vloga as vl
           ON pv.vloga_id = vl.id
           WHERE pv.prevod_id = p.id
           GROUP BY pv.prevod_id
       ) as 'vloge'
FROM clan as c
JOIN prevod as p
ON c.id = p.id_clan
JOIN jezik as iz
ON p.iz_id = iz.id
JOIN jezik as v
ON p.v_id = v.id
WHERE c.objava_v_iskalniku = 1
;`, (err, rows, fields)=> {
        if (err) throw err;

        // Group prevodi per user
        let out = [];
        for (let row of rows) {
            if (out.length <= 0 || out[out.length - 1].id !== row.id) {
                out.push({
                    "id": row.id,
                    "ime": row.ime,
                    "priimek": row.priimek,
                    "spol": row.spol,
                    "telefondoma": row.telefondoma,
                    "telefonmobi": row.telefonmobi,
                    "telefonsluzba": row.telefonsluzba,
                    "email": row.email,
                    "spletnastran": row.spletnastran,
                    "prevodi": [],
                });
            }
            out[out.length - 1].prevodi.push({
                "rang": row.rang,
                "iz": row.iz,
                "v": row.v,
                "strokovnopodrocje": row.podrocja?.split(';'),
                "vloga": row.vloge?.split(';'),
            });
        }
        res.send(JSON.stringify(out, null, 4));
    });
})


// app.listen(PORT, () => {
//     console.log(`Server listening on port ${PORT}`);
// });