<?php
    $_id = isset($_GET['i']) ? intval($_GET['i']) : 0;
    $_name = isset($_POST['name']) ? trim(strval($_POST['name'])) : ''; 

    $community = mysqli_query_logged("SELECT * FROM community WHERE community_id = " . sq($_id));
    if (!$community_row = mysqli_fetch_assoc($community))
    {
        make_cookie('notice', 'Sorry, but this community does not exist.');
        header('Location: ./?s=community_create');
        die;
    }

    require_once('include/functions/community_permissions.php');
    community_permissions($community_row['community_id']);
    
    if (!$GLOBALS['auth']['community']['administration'])
    {
        make_cookie('notice', 'Sorry, you don\'t have permission to modify this community.');
        header('Location: ./?s=community_create');
        die;
    }
    
    require_once('include/functions/community_section_valid.php');
    if ($error = community_section_valid($_name))    
    {
        make_cookie('notice', $error);
        header('Location: ./?s=community_modify&i=' . $community_row['id']);
        die;        
    }    
    
    $community_sections = mysqli_query_logged("SELECT * FROM community_sections WHERE community_id = '" . $community_row['community_id'] . "' ORDER BY section_order_id DESC LIMIT 1");
    if ($community_sections_row = mysqli_fetch_assoc($community_sections))
    {
        $order_id = $community_sections_row['section_order_id'] + 1;
    }
    else
    {
        $order_id = 0;
    }

    mysqli_query_logged("INSERT INTO community_sections SET community_id = '" . $community_row['community_id'] . "', section_name_english = " . sq($_name) . ", section_name_french = " . sq($_name) . ", section_order_id = '" . $order_id . "'");
    $mysql_insert_id = mysqli_insert_id($GLOBALS['mysqli']);
    mysqli_query_logged("INSERT INTO community_forums SET section_id = '" . $mysql_insert_id . "', forum_name_english = 'Untitled Forum', forum_name_french = 'Untitled Forum', forum_description_english = 'The quick brown fox jumps over the lazy dog.', forum_description_french = 'The quick brown fox jumps over the lazy dog.', forum_order_id = '0'");
    
    header('Location: ./?s=community_modify&i=' . $community_row['community_id']);
    die;
?>