<?php
    /*
        *****************************************************************************
        * MEGA Digital Space - by MEGA Digital Studio                               *
        * ------------------------------------------------------------------------- *
        * CMS Website:  https://megadigital.space                                   *
        * License:  https://megadigital.space/license                               *
        * Owner:  Giorgi Basharuli                                                  *
        * Contact:  online@megadigital.studio                                       *
        * MEGA Digital Studio – Official Development Studio for MEGA Digital Space  *
        * Website:  https://megadigital.studio                                      *
        * ------------------------------------------------------------------------- *
        * Description: This file is a part of the MEGA Digital Space CMS system.    *
        * Unauthorized distribution, modification, or commercial use is strictly -  *
        * prohibited without prior written permission.                              *
        * ------------------------------------------------------------------------- *
        * Copyright (c) 2023-2025 MEGA Digital Studio.                              *
        * All rights reserved.                                                      *
        *****************************************************************************
    */

    require_once(ENGINE_DIR . '/data/config.php');
    require_once ENGINE_DIR.'/payment/systems/general_config.php';
    require_once ENGINE_DIR.'/mods/convert_user_balance.php';
    require_once(ENGINE_DIR."/mods/database_helper.php");

    function facebookAuth() {
        global $db_connect, $smarty, $config, $ps_config, $user_id, $lang;

        session_start();

        $fb = new \Facebook\Facebook([
            'app_id' => $config["fb_settings"]["app_id"],
            'app_secret' => $config["fb_settings"]["client_secret"],
            'default_graph_version' => $config["fb_settings"]["default_graph_version"],
        ]);

        $helper = $fb->getRedirectLoginHelper();

        if (isset($_GET['state'])) {
            $helper->getPersistentDataHandler()->set('state', $_GET['state']);
        }

        try {
            $accessToken = $helper->getAccessToken();
        } catch(\Facebook\Exceptions\FacebookResponseException $e) {
            throw new Exception('Graph returned an error: ' . $e->getMessage());
        } catch(\Facebook\Exceptions\FacebookSDKException $e) {
            throw new Exception('Facebook SDK error: ' . $e->getMessage());
        }

        if (!isset($accessToken)) {
            header("Location: /");
        }

        $accessTokenStr = (string) $accessToken;
        $_SESSION['fb_access_token'] = $accessTokenStr;

        try {
            $response = $fb->get('/me?fields=id,name,email,picture', $accessTokenStr);
            $me = $response->getGraphUser();

            $facebookId = $me->getId();
            $name = $me->getName();
            $email = $me->getEmail();
            $avatar = $me->getPicture()->getUrl();

            $lastRecord = $db_connect->get("users", "id", [
                "ORDER" => ["id" => "DESC"],
                "LIMIT" => 1
            ]);

            $image = "uploads/profiles/default.svg";
            if (!empty($avatar)) {
                $dir = 'uploads/profiles/' . date('Y') . '/' . date('m') . '/' . ($lastRecord + 1) . '/';
                $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/' . $dir;
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }

                $file_count = count(scandir($uploadDir)) - 2;
                $ext = pathinfo(parse_url($avatar, PHP_URL_PATH), PATHINFO_EXTENSION);
                if (!$ext) $ext = 'jpg';
                $imageName = $p_id . '_' . $file_count . '.' . $ext;
                $imagePath = $uploadDir . $imageName;

                $imageContent = file_get_contents($avatar);
                if ($imageContent !== false && file_put_contents($imagePath, $imageContent) !== false) {
                    $image = $dir . $imageName;
                }
            }


            $existsUser = $db_connect->has("users", ["email" => $email]);
            if (!$existsUser) {
                $db_connect->insert("users", ["auth_source" => "facebook", "email" => $email, "name" => $name, "avatar" => $image, "group" => 6]);
            }

            $db_connect->update("users", ["avatar" => $image], ["email" => $email]);

            $user = $db_connect->get("users", "*", [
                "email" => $email,
            ]);

            $_SESSION['user_id'] = $user["id"];
            $_SESSION['user_name'] = $user["name"];
            $_SESSION['user_email'] = $user["email"];
            $_SESSION['user_authenticated'] = true;
            $_SESSION['user_group_id'] = $user["group"];

            // Здесь сделай проверку в БД — если юзер уже есть, логиним; если нет — регистрируем.
            header("Location: /");
            exit;

        } catch (\Exception $e) {
            exit('Error getting user: ' . $e->getMessage());
        }

    }