<?php

session_start();

require '../../config.php';
require '../admin_config.php';
require '../functions.php';

if (isset($_SESSION['user_email'])){

$connect = connect($database);

$check_access = check_access($connect);

if ($check_access['user_role'] == 1){

// Get current Firebase config
$query = $connect->query("SELECT * FROM firebase_config WHERE config_id = 1");
$firebaseConfig = $query->fetch(PDO::FETCH_ASSOC);

// Get settings
$settingsQuery = $connect->query("SELECT * FROM settings WHERE id = 1");
$settings = $settingsQuery->fetch(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    
    $config_api_key = trim($_POST['config_api_key']);
    $config_auth_domain = trim($_POST['config_auth_domain']);
    $config_project_id = trim($_POST['config_project_id']);
    $config_storage_bucket = trim($_POST['config_storage_bucket']);
    $config_messaging_sender_id = trim($_POST['config_messaging_sender_id']);
    $config_app_id = trim($_POST['config_app_id']);
    $config_measurement_id = trim($_POST['config_measurement_id']);
    $config_enabled = isset($_POST['config_enabled']) ? 1 : 0;
    
    $st_google_login = isset($_POST['st_google_login']) ? 1 : 0;
    $st_facebook_login = isset($_POST['st_facebook_login']) ? 1 : 0;
    $st_mobile_otp_login = isset($_POST['st_mobile_otp_login']) ? 1 : 0;
    
    // Update Firebase config
    $updateConfig = $connect->prepare("UPDATE firebase_config SET 
        config_api_key = ?,
        config_auth_domain = ?,
        config_project_id = ?,
        config_storage_bucket = ?,
        config_messaging_sender_id = ?,
        config_app_id = ?,
        config_measurement_id = ?,
        config_enabled = ?
        WHERE config_id = 1");
    
    $updateConfig->execute([
        $config_api_key,
        $config_auth_domain,
        $config_project_id,
        $config_storage_bucket,
        $config_messaging_sender_id,
        $config_app_id,
        $config_measurement_id,
        $config_enabled
    ]);
    
    // Update settings
    $updateSettings = $connect->prepare("UPDATE settings SET 
        st_google_login = ?,
        st_facebook_login = ?,
        st_mobile_otp_login = ?
        WHERE id = 1");
    
    $updateSettings->execute([
        $st_google_login,
        $st_facebook_login,
        $st_mobile_otp_login
    ]);
    
    $_SESSION['firebase_success'] = 'Firebase configuration updated successfully!';
    header('Location: ./firebase_config.php');
    exit;
}

require '../views/header.view.php';
require '../views/firebase_config.view.php';

}else{
    header('Location:'.SITE_URL);
}

require '../views/footer.view.php';

}else{
    header('Location: ./login.php');
}

?>
