<?_info
nocache=>1
_info?><?page
title=><?_code return $FORM{'id'} ? "Edit FAQ Item #$FORM{'id'}" : "Add to FAQ"; _code?>
body<=

<CENTER>
<A HREF="./"><B>(Back to FAQ Index)</B></A>
</CENTER>
<P>

<?_code

 my $dbh = LJ::get_db_writer();

 my $remote = LJ::get_remote();
 my %ac_edit;
 my %ac_add;

 $id = $FORM{'id'} + 0;
 $ret = "";
  
 $qq = $dbh->quote($FORM{'q'});
 $qa = $dbh->quote($FORM{'a'});
 $qfaqcat = $dbh->quote($FORM{'faqcat'});
 
 $sortorder = $FORM{'sortorder'}+0 || 50;

 return "<?requirepost?>" unless LJ::did_post();
 
 if ($id)
 {
     LJ::remote_has_priv($remote, "faqedit", \%ac_edit);
     my $sth = $dbh->prepare("SELECT faqcat FROM faq WHERE faqid=$id");
     $sth->execute;
     my ($faqcat) = $sth->fetchrow_array;

     unless ($ac_edit{'*'} || $ac_edit{$faqcat}) {
         if (%ac_edit) {
             return "<B>Error: </B> You do not have access to edit a FAQ question in the \"$faqcat\" category.";
         } else {
             return "<B>Error: </B> You do not have access to edit the FAQ.";
         }
     }
 }
 else 
 {
     LJ::remote_has_priv($remote, "faqadd", \%ac_add);
     unless ($ac_add{'*'} || $ac_add{$FORM{'faqcat'}}) {
         return "<B>Error: </B> You do not have access to add FAQ questions in this category";
     }     
 }

 my $faqd = LJ::Lang::get_dom("faq");
 my $rlang = LJ::Lang::get_root_lang($faqd);
 unless ($rlang) { undef $faqd; }
 my $opts = {
     'changeseverity' => $FORM{'sev'}+0,
 };
 my $do_trans = sub {
     my $id = shift;
     return unless $faqd;
     LJ::Lang::set_text($dbh, $faqd->{'dmid'}, $rlang->{'lncode'},
                        "$id.1question", $FORM{'q'}, $opts);
     LJ::Lang::set_text($dbh, $faqd->{'dmid'}, $rlang->{'lncode'},
                        "$id.2answer", $FORM{'a'}, $opts);
 };
 
 unless ($id)
 {
     unless ($FORM{'faqcat'})
     {
         return "<B>Error: </B> You did not select a FAQ category.";
     }
     $dbh->do("INSERT INTO faq (faqid, question, answer, faqcat, sortorder, lastmoduserid, lastmodtime) VALUES (NULL, $qq, $qa, $qfaqcat, $sortorder, $remote->{'userid'}, NOW())");
     $id = $dbh->{'mysql_insertid'};
     $ret .= $dbh->errstr || "Added FAQ item.  All good.";

     $opts->{'childrenlatest'} = 1; 
     $do_trans->($id) if $id;
 }
 else
 {

     if ($FORM{'q'} =~ /\S/)
     {
         $dbh->do("UPDATE faq SET question=$qq, answer=$qa, faqcat=$qfaqcat, lastmoduserid=$remote->{'userid'}, lastmodtime=NOW(), sortorder=$sortorder WHERE faqid=$id");
         $ret .= "Updated FAQ item.  All good.  faqid is <b><a href='$LJ::SITEROOT/support/faqbrowse.bml?faqid=$id'>$id</a></b>";

         $do_trans->($id);
     }
     else
     {
         $dbh->do("DELETE FROM faq WHERE faqid=$id");
         $ret .= "FAQ item deleted.";

         # TODO: delete translation from ml_* ?
     }
 }
 
 return $ret;
 
_code?>

<=body
page?><?_c <LJDEP>
lib: cgi-bin/ljlib.pl
link: htdocs/admin/faq/index.bml
</LJDEP> _c?>
