<?php
include("connectSQL_Component.php");


if (isset($_POST["AddFavorite"])) {

    $favorite = $_POST["AddFavorite"];
    $username = $_POST["username"];
    $revitVersion = $_POST["revitVersion"];
    $sql = "BEGIN
                    IF NOT EXISTS (SELECT * FROM [BIMComponents].[dbo].[Favorite_Table] 
                        WHERE [favorite] = '" . $favorite . "' AND [user_name] = '" . $username . "')
                    BEGIN
                        INSERT INTO [BIMComponents].[dbo].[Favorite_Table]
                                ([user_name]
                                ,[favorite]
                                ,[revitVersion])
                            VALUES
                                ('" . $username . "'
                                ,'" . $favorite . "'
                                ,'" . $revitVersion . "')
                    END
                END";
    sqlsrv_query($conn, $sql);
} else if (isset($_POST["DelFavorite"])) {

    $favorite = $_POST["DelFavorite"];
    $username = $_POST["username"];
    $sql = "BEGIN
                    IF EXISTS (SELECT * FROM [BIMComponents].[dbo].[Favorite_Table] 
                                    WHERE [favorite] = '" . $favorite . "' AND [user_name] = '" . $username . "')
                    BEGIN
                        DELETE FROM [BIMComponents].[dbo].[Favorite_Table] 
                        WHERE [favorite] = '" . $favorite . "' AND [user_name] = '" . $username . "'
                    END
                END";
    sqlsrv_query($conn, $sql);
} else if (isset($_GET["CheckFavorite"])) {
    $favorite = $_GET["CheckFavorite"];
    $sql = "SELECT * FROM [BIMComponents].[dbo].[Favorite_Table] Where [favorite] = '" . $favorite . "' AND [user_name] = '" . $_SESSION["name"] . "';";
    $i = 0;
    $fetchResult = sqlsrv_query($conn, $sql);
    while ($row = sqlsrv_fetch_array($fetchResult, SQLSRV_FETCH_NUMERIC)) {
        $i++;
    }
    if ($i > 0) {
        $result = true;       
    } else {
        $result = false;        
    }
    echo json_encode($result);
} else if (isset($_POST["delFavoriteList"])) {

    $delFavoriteList = $_POST["delFavoriteList"];
    $username = $_POST["username"];
    
    foreach ($delFavoriteList as $key => $value) {
        $sql = "BEGIN
            IF EXISTS (SELECT * FROM [BIMComponents].[dbo].[Favorite_Table] 
                            WHERE [id] = '" . $value . "' AND [user_name] = '" . $username . "')
            BEGIN
                DELETE FROM [BIMComponents].[dbo].[Favorite_Table] 
                WHERE [id] = '" . $value . "' AND [user_name] = '" . $username . "'
            END
        END";
        sqlsrv_query($conn, $sql);
    }
    
}

sqlsrv_close($conn);
