package Admin::Category;
use strict;
#################################################################################
# Ikonboard v3 by Jarvis Entertainment Group, Inc.
#
# No part of this script can be used outside Ikonboard without prior consent.
#
# More information available from <ib-license@jarvisgroup.net>
# (c)2001-2002 Jarvis Entertainment Group, Inc.
# 
# http://www.ikonboard.com | http://www.jarvisgroup.net
#
# Please read the license for more information
#
# 
#
#################################################################################

BEGIN {
    require 'Lib/FUNC.pm';
    require 'Lib/ADMIN.pm';
    require 'Admin/SKIN.pm';
    require 'Boardinfo.pm' or die "Cannot load Module: $!";
}

my $SKIN  = Admin::SKIN->new();
my $std   = FUNC::STD->new();
my $mem   = FUNC::Member->new();
my $ADMIN = FUNC::ADMIN->new();
my $INFO  = Boardinfo->new();

sub new {
    my $pkg = shift;
    my $obj = {};
    bless $obj, $pkg;
    return $obj;
}

#+---------------------------------------------------------------------------------------------------------

sub splash {
    my ($obj, $db) = @_;

    $obj->print_list( CODE   => '00',
                      BUTTON => 'Edit Selected Category',
                      TYPE   => 'radio',
                      TEXT   => 'Choose Categories to Edit',
                      DB     => $db
                    );
}


sub delete {
    my ($obj, $db) = @_;

    $obj->print_list( CODE   => 'dodel',
                      BUTTON => 'Remove Selected Category',
                      TYPE   => 'radio',
                      TEXT   => 'Choose a Category to Remove',
                      DB     => $db
                    );
}


sub reorder {
    my ($obj, $db) = @_;

    $obj->print_list( CODE   => 'doreorder',
                      BUTTON => 'Reorder the categories',
                      TYPE   => 'REORDER',
                      TEXT   => 'Reorder your categories',
                      DB     => $db
                    );
}

sub print_list {
    my $obj = shift;

    my %IN = ( CODE    => "",
               BUTTON  => "",
               TYPE    => "",
               TEXT    => "",
               DB      => "",
               @_,
              );

    my $db = $IN{'DB'};

    $obj->{'TOTAL_CATS'}   = $db->query(TABLE     => 'categories',
                                        COLUMNS   => ['CAT_NAME', 'CAT_ID', 'CAT_POS'],
                                        SORT_KEY  => 'CAT_POS',
                                        SORT_BY   => 'A-Z',
                                        MATCH     => 'ALL',
                                      ) || die $db->{'error'};

    $obj->{'TOTAL_FORUMS'} = $db->query(TABLE     => 'forum_info',
                                        SORT_KEY  => 'FORUM_POSITION',
                                        SORT_BY   => 'A-Z',
                                        MATCH     => 'ALL'
                                      ) || die $db->{'error'};

    my $nbsp = $IN{'TYPE'} eq 'REORDER' ? 'Position' : '&nbsp;';

    my $html = qq~

    <table cellspacing='0' cellpadding='5' border='0' width='100%' border='0'>
    <tr>
    <td>
    <font class='large'>&gt;&gt; Your Categories</font>
    <br><font class='t'>&nbsp;&nbsp;&nbsp;&nbsp;$IN{'TEXT'}</font>
    
    <form action='$INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?AD=1&act=cat&s=$iB::SESSION&CODE=00' method='post'>
    <input type='hidden' name='AD' value='1'>
    <input type='hidden' name='act' value='cat'>
    <input type='hidden' name='s' value='$iB::SESSION'>
    <input type='hidden' name='CODE' value='$IN{'CODE'}'>

    <table cellspacing='1' cellpadding='0' width='100%' align='center' border='0' bgcolor='#333366'>
        <tr>
            <td>
            <table cellspacing='1' cellpadding='2' width='100%' align='center' border='0'>
            <tr>
            <td bgcolor='#8888AA' width='10%' align='center'><font class='t' style='color:white'>$nbsp</font></td>
            <td bgcolor='#8888AA' width='30%'><font class='t' style='color:white'><b>Category Name</b></font></td>
            <td bgcolor='#8888AA' width='15%' align='center'><font class='t' style='color:white'><b>Total Forums</b></font></td>
            <td bgcolor='#8888AA' width='8%' align='center'><font class='t' style='color:white'><b>Total Topics</b></font></td>
            <td bgcolor='#8888AA' width='8%' align='center'><font class='t' style='color:white'><b>Total Posts</b></font></td>
            <td bgcolor='#8888AA' width='30%'><font class='t' style='color:white'><b>Last Post</b></font></td>
            </tr>
    ~;


    for my $this_cat (@{ $obj->{'TOTAL_CATS'} }) {

        for my $forum (grep { $_->{'CATEGORY'} == $this_cat->{'CAT_ID'} } @{ $obj->{'TOTAL_FORUMS'} }) {
            $this_cat->{'TOTAL_FORUMS'} += 1;
            $this_cat->{'TOTAL_POSTS'} += $forum->{'FORUM_POSTS'};
            $this_cat->{'TOTAL_TOPICS'} += $forum->{'FORUM_TOPICS'};
            $this_cat->{'LAST_POST'} = $forum->{'FORUM_LAST_POST'} if $forum->{'FORUM_LAST_POST'} > $this_cat->{'LAST_POST'};
        }

        $this_cat->{'LAST_POST'} = $this_cat->{'LAST_POST'} ? $std->get_date(TIME=>$this_cat->{'LAST_POST'}, METHOD=>'LONG')
                                                            : 'never';

        my $radio_check = qq!<input type='$IN{'TYPE'}' name='c' value='$this_cat->{'CAT_ID'}' style='border:none'>!;

        if ($IN{'TYPE'} eq 'REORDER') {
            my $total_cats = scalar @{$obj->{'TOTAL_CATS'}};
            my $select = qq!<select name='CAT_ID_$this_cat->{'CAT_ID'}'>\n!;
            for (1 .. $total_cats) {
                $select .= qq!<option value='$_'>&nbsp;$_&nbsp;</option>\n!;
            }
            $select =~ s!value='$this_cat->{'CAT_POS'}'>!value='$this_cat->{'CAT_POS'}' selected>!;
            $radio_check = $select . "</select>";
        }


        $html .= qq~

            <tr>
            <td bgcolor='#FFFFFF' align='center'>$radio_check</td>
            <td bgcolor='#FFFFFF'><font class='t'>$this_cat->{'CAT_NAME'}</font></td>
            <td bgcolor='#FFFFFF' align='center'><font class='t'>$this_cat->{'TOTAL_FORUMS'}</font></td>
            <td bgcolor='#FFFFFF' align='center'><font class='t'>$this_cat->{'TOTAL_TOPICS'}</font></td>
            <td bgcolor='#FFFFFF' align='center'><font class='t'>$this_cat->{'TOTAL_POSTS'}</font></td>
            <td bgcolor='#FFFFFF'><font class='t'>$this_cat->{'LAST_POST'}</font></td>
            </tr>

        ~;
    }

    $html .= qq~
            
            <tr>
            <td colspan='6' align='center' bgcolor='#FFFFFF'><br><input type='submit' value='$IN{'BUTTON'}'></td>
            </tr>
            </table>
         </td>
        </tr>
      </table>
     </form>
    </td>
    </tr>
    </table>
    ~;


    $ADMIN->Output( WHERE => 'CATS', NAV_ONE => 'Category Control', PRINT => $html);

}

#+---------------------------------------------------------------------------------------------------------

sub add_form {
    my ($obj, $db) = @_;

    my $html  = $SKIN->title( TITLE => 'Create a New Category', TEXT => 'Please note, that the category will not be displayed on the board until a forum has been assigned to it.' );
       $html .= $SKIN->begin_table();
       $html .= $SKIN->form_start();
       $html .= $SKIN->hidden_fields( { act   => 'cat',
                                        CODE  => '03'
                                      } );

    my $non_sub_cats = $db->query( TABLE    => 'categories',
                                   WHERE    => qq|SUB_CAT_ID == 0|,
                                   SORT_KEY => 'CAT_NAME'
                                 );

    my $mem_groups = $db->query( TABLE      => 'mem_groups',
                                 COLUMNS    => ['ID', 'TITLE', 'CAN_REMOVE'],
                                 SORT_KEY   => 'TITLE',
                                 SORT_BY    => 'A-Z',
                               );

    my @permitted;

    for (@{$mem_groups}) {
        push @permitted, { NAME => $_->{'TITLE'}, VALUE => $_->{'ID'} };
    }

    unshift @permitted, { NAME => '#ALL MEMBER GROUPS#',     VALUE => '*' };

    my $size   = scalar (@permitted) + 1;

    #+-----------------------------------

    $html .= $SKIN->section_header( TITLE => "Category Title" );

    $html .= $SKIN->td_input ( TEXT     => 'Category Title', NAME => 'cat_name', VALUE=> "", REQ => 1 );

    $html .= $SKIN->section_header( TITLE => "Base Mask", TEXT => "Please set the base reading permissions for all forums in this category.<br>&nbsp;&nbsp;&nbsp;&nbsp;ALL MEMBER GROUPS is relevant to all groups, current and any more you create" );

    $html .= $SKIN->td_select( TEXT     => 'Member Groups:',
                               NAME     => 'permission',
                               SIZE     => $size,
                               MULTIPLE => 1,
                               VALUES   => '*',
                               DATA     => \@permitted
                             );
    $html .= $SKIN->section_header( TITLE => "Display Settings" );
    #
    #$html .= $SKIN->td_select( TEXT     => 'Default View:',
    #                           NAME     => 'expand',
    #                           SIZE     => 2,
    #                           MULTIPLE => '',
    #                           REQ      => 1,
    #                           VALUES   => "*",
    #                           DATA     => [ { VALUE => 1, NAME => 'Expanded'  },
    #                                         { VALUE => 0, NAME => 'Collapsed' },
    #                                       ]
    #                         );
    #
    $html .= $SKIN->td_select( TEXT     => 'Turn this category:',
                               NAME     => 'state',
                               SIZE     => 2,
                               MULTIPLE => '',
                               REQ      => 1,
                               VALUES   => "1",
                               DATA     => [ { VALUE => 1, NAME => 'On'  },
                                             { VALUE => 0, NAME => 'Off' },
                                           ]
                             );

    $html .= $SKIN->section_header( TITLE => "Optional: Add Catagory Image (Can be used for Category sponsor, etc)" );
    $html .= $SKIN->td_input ( TEXT     => 'Image:<br>&nbsp;&nbsp;&nbsp;(add full URL of image, like:<br>&nbsp;&nbsp;&nbsp;http://www.domain.com/image.gif)', NAME => 'image', VALUE=> "", REQ => 0 );
    $html .= $SKIN->td_input ( TEXT     => 'Website URL:<br>&nbsp;&nbsp;&nbsp;(add full site, like:<br>&nbsp;&nbsp;&nbsp;http://www.domain.com)', NAME => 'url', VALUE=> "", REQ => 0 );

    if (scalar @{$non_sub_cats} > 0) {
        
        my @non_subs;
        push @non_subs, { VALUE => '0', NAME => "NONE (don't make sub category)" };

        for (@{$non_sub_cats}) {
            push @non_subs, { VALUE => $_->{'CAT_ID'}, NAME => $_->{'CAT_NAME'} };
        }

        $html .= $SKIN->section_header( TITLE => "Make this a sub category?", TEXT => "If enabled, please choose which category to insert it into<br>&nbsp;&nbsp;&nbsp;&nbsp;Sub-Categories display just like forums in the board list (i.e. collapsed)" );

        $html .= $SKIN->td_select( TEXT     => 'Make a sub category of:',
                                   NAME     => 'make_sub',
                                   SIZE     => 1,
                                   VALUES   => '',
                                   DATA     => \@non_subs
                             );

        $html .= $SKIN->td_textarea( TEXT => "Description of sub-category", NAME => 'cat_desc', VALUE => '' );
    }

    else {
    
        $html .= $SKIN->hidden_fields( { make_sub   => '0' } );
    }

    
    $html .= $SKIN->td_submit(   NAME => '', VALUE => 'Add Category' );


    $html .= $SKIN->form_end();
    $html .= $SKIN->end_table();

    #+-----------------------------------

    $ADMIN->Output( WHERE => 'CATS', NAV_ONE => qq[<a href='$INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?AD=1&s=$iB::SESSION&act=cat' target='BODY'>Category Control</a>], NAV_TWO => "Adding a new Category", PRINT => $html);


}



sub doreorder {
    my ($obj, $db) = @_;

    my $cats   = $db->query( TABLE => 'categories' ) || die $db->{'error'};

    for my $cat (@{$cats}) {

        $db->update( TABLE  => 'categories',
                     KEY    => $cat->{'CAT_ID'},
                     VALUES => { CAT_POS => $iB::IN{ 'CAT_ID_'.$cat->{'CAT_ID'} } }
                   );
    }

    $ADMIN->pure_redirect( URL => "act=cat&CODE=reorder" );

}


sub add_cat {
    my ($obj, $db) = @_;

    $ADMIN->Error( DB => $db, STD => $std, MSG => "You must enter a Category Title") unless $iB::IN{'cat_name'};
    
    my $cats;
    my $cat   = $db->query(TABLE     => 'categories' );

    for my $c (@{$cat}) {
        if ($c->{'CAT_ID'} > $cats) {
            $cats = $c->{'CAT_ID'};
        }
    }

    ++$cats;

    my $view;
    if (grep { /\*/ } $iB::CGI->param('permission')) {
        $view = '*';
    } else {
        $view = join ",", $iB::CGI->param('permission');
    }

    $db->insert( TABLE  => 'categories',
                 VALUES => { 
                             CAT_POS     => $cats,
                             CAT_STATE   => $iB::IN{'state'},
                             CAT_NAME    => $iB::IN{'cat_name'},
                             CAT_DESC    => $iB::IN{'cat_desc'},
                             SUB_CAT_ID  => $iB::IN{'make_sub'},
                             IMAGE       => $iB::IN{'image'},
                             URL         => $iB::IN{'url'},
                             VIEW        => $view
                           }
              );

    &iB::catch_die( $db->error ) if $db->error;

    $ADMIN->pure_redirect( URL => "act=cat" );

}

#+---------------------------------------------------------------------------------------------------------

sub view_detail {
    my ($obj, $db) = @_;

    $ADMIN->Error( DB => $db, STD => $std, MSG=>'no_cat') unless defined $iB::IN{'c'};

    my $cat = $db->select( TABLE     => 'categories',
                           KEY       => $obj->{'.cat_id'},
                         );

    $ADMIN->Error( DB => $db, STD => $std, MSG=>'no_cat') unless defined $cat->{'CAT_ID'};

    my $non_sub_cats = $db->query( TABLE    => 'categories',
                                   WHERE    => qq|SUB_CAT_ID == "0"  and CAT_ID != "$cat->{CAT_ID}"|,
                                   SORT_KEY => 'CAT_NAME'
                                 );


    my $html  = $SKIN->title( TITLE => 'Category Details', TEXT => 'You may edit the following details' );
       $html .= $SKIN->begin_table();
       $html .= $SKIN->form_start();
       $html .= $SKIN->hidden_fields( { act   => 'cat',
                                        c     => $cat->{'CAT_ID'},
                                        CODE  => '01'
                                      } );

    # Hands up who loves idiomatic perl?
    # Hands up who loves the spaceship operator?
    # Hands up if you've got both hands up.

    my $mem_groups = $db->query( TABLE      => 'mem_groups',
                                 COLUMNS    => ['ID', 'TITLE', 'CAN_REMOVE'],
                                 SORT_KEY   => 'TITLE',
                                 SORT_BY    => 'A-Z',
                               );

    my @permitted;

    for (@{$mem_groups}) {
        push @permitted, { NAME => $_->{'TITLE'}, VALUE => $_->{'ID'} };
    }

    my @view  = $cat->{'VIEW'} !~ /,/ 
              ? ( 
                  $cat->{'VIEW'} eq '*' 
                    ? ( '*' )
                    : ( 'c' )
                )
              : (split/,/,$cat->{'VIEW'});

    unshift @permitted, { NAME => '#ALL MEMBER GROUPS#',     VALUE => '*' };


    my $size   = scalar (@permitted) + 1;


    $html .= $SKIN->section_header( TITLE => "Category Title" );

    $html .= $SKIN->td_input ( TEXT     => 'Category Title', NAME => 'cat_name', VALUE=> $cat->{'CAT_NAME'}, REQ => 1 );

    $html .= $SKIN->section_header( TITLE => "Base Mask", TEXT => "Please set the base reading permissions for all forums in this category.<br>&nbsp;&nbsp;&nbsp;&nbsp;ALL MEMBER GROUPS is relevant to all groups, current and any more you create" );

    $html .= $SKIN->td_select( TEXT     => 'Member Groups:',
                               NAME     => 'permission',
                               SIZE     => $size,
                               MULTIPLE => 1,
                               VALUES   => \@view,
                               DATA     => \@permitted,
                             );

    $html .= $SKIN->section_header( TITLE => "Display Settings" );
    
    $html .= $SKIN->td_select( TEXT     => 'Turn this category:',
                               NAME     => 'state',
                               SIZE     => 2,
                               MULTIPLE => '',
                               REQ      => 1,
                               VALUES   => $cat->{'CAT_STATE'},
                               DATA     => [ { VALUE => 1, NAME => 'On'  },
                                             { VALUE => 0, NAME => 'Off' },
                                           ]
                             );

    $html .= $SKIN->section_header( TITLE => "Optional: Add Catagory Image (Can be used for Category sponsor, etc)" );
    $html .= $SKIN->td_input ( TEXT     => 'Image:<br>&nbsp;&nbsp;&nbsp;(add full URL of image, like:<br>&nbsp;&nbsp;&nbsp;http://www.domain.com/image.gif)', NAME => 'image', VALUE=> "$cat->{'IMAGE'}", REQ => 0 );
    $html .= $SKIN->td_input ( TEXT     => 'Website URL:<br>&nbsp;&nbsp;&nbsp;(add full site, like:<br>&nbsp;&nbsp;&nbsp;http://www.domain.com)', NAME => 'url', VALUE=> "$cat->{'URL'}", REQ => 0 );


    if (scalar @{$non_sub_cats} > 0) {
        
        my @non_subs;
        push @non_subs, { VALUE => '0', NAME => "NONE (don't make sub category)" };

        for (@{$non_sub_cats}) {
            push @non_subs, { VALUE => $_->{'CAT_ID'}, NAME => $_->{'CAT_NAME'} };
        }

        $html .= $SKIN->section_header( TITLE => "Make this a sub category?", TEXT => "If enabled, please choose which category to insert it into<br>&nbsp;&nbsp;&nbsp;&nbsp;Sub-Categories display just like forums in the board list (i.e. collapsed)" );

        $html .= $SKIN->td_select( TEXT     => 'Make a sub category of:',
                                   NAME     => 'make_sub',
                                   SIZE     => 1,
                                   VALUES   => $cat->{'SUB_CAT_ID'},
                                   DATA     => \@non_subs
                             );

        $html .= $SKIN->td_textarea( TEXT => "Description of sub-category", NAME => 'cat_desc', VALUE => $cat->{'CAT_DESC'} );
    }

    else {
    
        $html .= $SKIN->hidden_fields( { make_sub   => '0' } );
    }

    $html .= $SKIN->td_submit(   NAME => '', VALUE => 'Apply Changes' );

    $html .= $SKIN->form_end();
    $html .= $SKIN->end_table();

    $ADMIN->Output( WHERE => 'CATS', NAV_ONE => qq[<a href='$INFO->{'BOARD_URL'}/ikonboard.$iB::INFO->{'CGI_EXT'}?AD=1&s=$iB::SESSION&act=cat' target='BODY'>Category Control</a>], NAV_TWO => "Editing $cat->{'CAT_NAME'}", PRINT => $html);


}


sub modify {
    my ($obj, $db) = @_;

    $ADMIN->Error( DB => $db, STD => $std, MSG => "No category ID selected, please try again") unless defined $obj->{'.cat_id'};

    $ADMIN->Error( DB => $db, STD => $std, MSG => "You must enter a Category Title") unless $iB::IN{'cat_name'};

    my $view;
    if (grep { /\*/ } $iB::CGI->param('permission')) {
        $view = '*';
    } else {
        $view = join ",", $iB::CGI->param('permission');
    }
  
    $db->update( TABLE  => 'categories',
                 KEY    => $obj->{'.cat_id'},
                 VALUES => { CAT_STATE   => $iB::IN{'state'},
                             CAT_NAME    => $iB::IN{'cat_name'},
                             CAT_DESC    => $iB::IN{'cat_desc'},
                             SUB_CAT_ID  => $iB::IN{'make_sub'},
                             IMAGE       => $iB::IN{'image'},
                             URL         => $iB::IN{'url'},
                             VIEW        => $view
                           }
              ) || $ADMIN->Error( DB => $db, STD => $std, MSG => $db->{'error'} );
    $ADMIN->pure_redirect( URL => "act=cat" );
}


sub dodelete {
    my ($obj, $db) = @_;
    my @the_cats;

    $ADMIN->Error( DB => $db, STD => $std, MSG => "No category ID selected, please try again") unless defined $obj->{'.cat_id'};

    my $forums   = $db->query( TABLE    => 'forum_info',
                               WHERE    => qq|CATEGORY == "$iB::IN{'c'}"|,
                             );

    if ((scalar (@{$forums}) > 0) and ($iB::IN{'MOVE'} != 1)) {

        my $cats = $db->query( TABLE    => 'categories',
                               WHERE    => qq|CAT_ID != "$iB::IN{'c'}"|,
                               SORT_KEY => 'CAT_NAME'
                             );
        

        my $html  = $SKIN->title( TITLE => 'Category Removal', TEXT => 'WARNING: This Category has active forums!' );
        $html .= $SKIN->begin_table();
        $html .= $SKIN->form_start();
        $html .= $SKIN->hidden_fields( { act   => 'cat',
                                         c     => $iB::IN{'c'},
                                         CODE  => 'dodel',
                                         MOVE  => 1,
                                      } );

        for (@{$cats}) {
            push @the_cats, { VALUE => $_->{'CAT_ID'}, NAME => $_->{'CAT_NAME'} };
        }

        $html .= $SKIN->section_header( TITLE => "Move forums to which category before deleting?");

        $html .= $SKIN->td_select( TEXT     => 'Category:',
                                   NAME     => 'TO_ID',
                                   SIZE     => 1,
                                   VALUES   => '',
                                   DATA     => \@the_cats
                             );

        $html .= $SKIN->td_submit(   NAME => '', VALUE => 'Move forums then remove this category' );

        $html .= $SKIN->form_end();
        $html .= $SKIN->end_table();

        $ADMIN->Output( WHERE => 'CATS', NAV_ONE => "Category Removal", PRINT => $html);

    }

    #XXX Are we moving forums first?

    if ($iB::IN{'MOVE'}) {
    
        $ADMIN->Error( DB => $db, STD => $std, MSG => "No category ID selected, please try again") unless defined $obj->{'.cat_id'};
        $ADMIN->Error( DB => $db, STD => $std, MSG => "No category ID selected to move forums to") unless defined $iB::IN{'TO_ID'};

        $db->update( TABLE   =>  'forum_info',
                     WHERE   =>  qq|CATEGORY == "$iB::IN{'c'}"|,
                     VALUES  =>  { CATEGORY  => $iB::IN{'TO_ID'} },
                   );

    }

    $db->delete( TABLE  => 'categories',
                 KEY    => $iB::IN{'c'}
               );

    $ADMIN->write_log( TITLE => 'Category Deleted');

    $ADMIN->static_screen( URL   => "act=cat&CODE=delete",
                           TITLE => "Category Removed",
                           TEXT  => "The database has been updated"
                         );
}







#+---------------------------------------------------------------------------------------------------------

sub process {
    my ($obj, $db) = @_;
    $obj->{'.cat_id'}   = $std->IsNumber($iB::IN{'c'});

    my %Mode = ( '00'        => \&view_detail,
                 '01'        => \&modify,
                 '02'        => \&add_form,
                 '03'        => \&add_cat,

                 'delete'    => \&delete,
                 'dodel'     => \&dodelete,

                 'reorder'   => \&reorder,
                 'doreorder' => \&doreorder,

               );
    $Mode{$iB::IN{'CODE'}} ? $Mode{$iB::IN{'CODE'}}->($obj,$db) : splash($obj,$db);
} 




1;
__END__









