#!/usr/local/bin/perl -w
# find.pl
# script to search domains on Classifieds page
#
# call from search: keyword(one),tld,category(multi),sorder
#
# if keyword, look in categories (if no cats?)
# if no key, show all in cats (primary)
# no key, all cats - error
#
#

use lib '/data1/hypermart.net/inamestore/aux/';
use Commodity;

$fdomain = "../aux/domains";                   # listed domains

$latest = 31;                                  # num of days, for recent

$quantum = 33;                                 # table split, if 0 - no

                                               # get the fields
%query = get_form_data("mode","keyword","keymode","tld",
                       "category","sorder")
                        or rest_in_peace("Invalid form data");

foreach $key (keys %query) {
    $$key = $query{$key};                      # assign it to vars
}                                              # with same names


$category =~ s/\+/|/g;                         # make it a pattern

if ($category =~ /\ball\b/) {$category = "all"};  # is it all?

$keyword = ($keyword =~ /([-\w]+)/g)[0];       # take only the 1st one

$mode = "nokey" if ($mode eq "search" and !$keyword);               
                                               # no keyword, show all
if ($mode eq "nokey" and $category eq "all") {
    reject_form("You should enter a keyword",
                " to search in all the categories simultaneously.<br>");
};

if ($mode eq "recent") {$sorder = "date"};     # showing recent

# now read the domains from file

open DOM, $fdomain or &rest_in_peace("Cannot open $fdomain: $!");

flock DOM, 1;                                  # is somebody writing?
seek DOM, 0, 0;

@domains = ();

DOMAIN: while(<DOM>) {

   next DOMAIN if /^#/;
   next DOMAIN if /^$/;

   chomp;
                                               # get the record
   my ($dname, $pdate, $cats, $price, $term, $wsite, 
       $keyws, $descr, $owner) = ( split /\t/, $_, -1 );
   
   my $primary = (split /,/, $cats, 3)[0];     # primary category

                                               # select what we need
   CHECK:{
      if ($mode eq "search") {                 
                                               # match top level     
         next DOMAIN unless ($dname =~ /$tld$/i or $tld eq "any");
                                               # category
         next DOMAIN unless ($cats =~ /\b$category\b/i 
                             or $category eq "all");
                                               # where to look?
         $stufftosearch = $dname if ($keymode == 1);  # just name 
         $stufftosearch = join(' ', $dname, $cats, $descr) 
	                        if ($keymode == 2);   # +cat,descr
         $stufftosearch = join(' ', $dname, $cats, $keyws, $descr) 
	                        if ($keymode == 3);   # everywhere      
         next DOMAIN unless ($stufftosearch =~ /$keyword/i);
#         maybe change to this when a lot of domains?
#         next DOMAIN unless ($stufftosearch =~ /\b$keyword/i);
         last CHECK;
      }  
      if ($mode eq "nokey") {                  # show only prime cats
         next DOMAIN unless ($dname =~ /$tld$/i or $tld eq "any");
         next DOMAIN unless ($primary =~ /\b$category\b/i);
         last CHECK;
      }  
      if ($mode eq "recent") {                 # $latest see above
         next DOMAIN unless is_recent($pdate, $latest);
         last CHECK;
      }  
      logerror("called in invalid mode");      # should not happen ;)
   }
      
   $dn = { 'dname'  => $dname,                 # put selected
           'pdate'  => $pdate,                 # into ref to hash
           'cats'   => $cats,
           'price'  => $price, 
           'term'   => $term, 
           'wsite'  => $wsite, 
           'keyws'  => $keyws,
           'descr'  => $descr,
           'owner'  => $owner,
           'prima'  => $primary,
         };

   push @domains, $dn;                         # put it in array
}

flock DOM, 8;                                  # free it
close DOM;


@domains = sort { &{"by$sorder"} } @domains;   # sort as asked


# now output the results - prepare some words

$total = @domains;                             # how many found

$items = "$total items" if ($total >= 2);
$items = "$total item"  if ($total == 1);
$items = "No items"     if ($total == 0);

$titleword = $keyword || "Selected categories";

$header_str = "Domain names matching <em>$keyword</em>: $items found" if ($mode eq "search");
$header_str = "Domain names in selected categories: $items found" if ($mode eq "nokey");
$header_str = "Domain names recently posted: $items found" if ($mode eq "recent");
$please_str = "Please click on the domain name to contact the seller" if $total;
$please_str = "Click <em>Back</em> button to search again" unless $total;


# the actual output
                                               # print header
html_out_header( "INameStore: Domain Classifieds - $titleword",
                 "Domain Classifieds" );

# local menu and <h> and table head
print <<__HEHE;
<a href="index.html">Another Search</a> -
<a href="find.pl?mode=recent">Recent Additions</a> -
<a href="dt/post.html">List Your Domain</a> -
<a href="sign.html">Create Account</a>
<hr>
<h3>
$header_str
</h3>
$please_str
<p>
__HEHE


# the table head
print <<__HEAD if $total;                      # something was found
<center>
<table width="100%" align="center">
  <tr>
    <td width="20%">
       <font color="804000"><b>Domain name</b></font>
    </td>
    <td width="10%" align="right">
       <font color="804000"><b>Price</b></font>
    </td>
    <td width="10%" align="center">
       <font color="804000"><b>Site</b></font>
    </td>
    <td width="15%">
       <font color="804000"><b>Category</b></font>
    </td>
    <td width="45%">
       <font color="804000"><b>Description</b></font>
    </td>
  </tr>
  <tr colspan="4"></tr>
</table>
__HEAD


                                               # the results go here
while (@domains and $total) {
    print '<table width="100%" align="center">';
  TT: for ($ii = 0; $ii<$quantum; $ii++) {
        last TT unless @domains;
        outdomain(shift @domains);
    }
    print '</table>';
}

                                               # closing banner and html

print <<__FOFO if $total > $quantum;
<hr>
<a href="index.html">Another Search</a> -
<a href="find.pl?mode=recent">Recent Additions</a> -
<a href="dt/post.html">List Your Domain</a> -
<a href="sign.html">Create Account</a>
<hr>
__FOFO


html_out_footer;

exit;



#############################
# outdomain REF2DOM
# prints out a domain record 
#
sub outdomain ($) {
    my $dom = $_[0]; 
    my $pri;
    if ($dom->{price}) {$pri = '$' . commify("$dom->{price}")} 
                  else {$pri = "Offer"}
    my $isws = '<a href="http://www.' . $dom->{dname} 
             . '" target="extsite">yes</a>' if $dom->{wsite};

    print <<__DDD;
<tr>
   <td width="20%">
      <a href="buy.pl?dname=$dom->{dname}&price=$dom->{price}">
      <b>$dom->{dname}</b>
   </td>
   <td width="10%" align="right">
      <b>$pri</b>
   </td width="10%">
   <td align="center" width="10%">
      <b>$isws</b>
   </td>
   <td width="15%">
      <b>$dom->{prima}</b>
   </td>
   <td width="45%" nowrap>
      $dom->{descr}
   </td>
</tr>
__DDD

} # end outdomain


##########################
#  is_recent YYYYMMDD, TERM
#         needs a proper cleaning !!!!
#  TERM - num of days
sub is_recent ($$) {
    my $date = $_[0];
    my $recent = $_[1];
    my ($y, $m, $d) = $date =~ /(....)(..)(..)/g;
    my ($cd, $cm, $cy) = (gmtime)[3,4,5]; 
    $cy += 1900;
    $cm++;
    my $diff = ($cy - $y)*365 + ($cm - $m)*30 + ($cd - $d);
    return $diff < $recent ? "yes" : "";
}


############################# sorting subs

sub byname {
    lc( $a->{dname} ) cmp lc( $b->{dname} );
};

sub bydate {                    # recent first
    $b->{pdate} <=> $a->{pdate}
    or                          # then by name
    lc( $a->{dname} ) cmp lc( $b->{dname} );
};

sub byprice {                   # costly first
#    (not $a->{price} and $b->{price})
#    or
    $b->{price} <=> $a->{price}
    or                          # then by name
    lc( $a->{dname} ) cmp lc( $b->{dname} );
};

sub bylength {
    length( $a->{dname} ) <=> length( $b->{dname} )
    or                          # then by name
    lc( $a->{dname} ) cmp lc( $b->{dname} );
};










