#!/usr/bin/perl

$| = 1;                 # Para que Perl no utilize su buffer

use DBI;                # Usar el DataBase Interface
use CGI qw/:standard/;  # Usar el GCI.pm module
use strict 'vars';

use vars '$dbh';                            # Database handler
use vars '$sth';                            # Statement handlers

###############################################################################

my $script_url = url(-absolute=>1);        # direccion absoluta del script
my $path = "/home/admin/public_html/notariasanchezmanrique/consulta";
my $clave = param('clave');
my $clave_geren = "588312";                # clave gerencial - acceso a todo

###############################################################################

print header(-expires=>'-10m');
print start_html(-title=>"Notaria Sanchez Manrique -  Consultas",
		 -style=>{'src'=>"/consultas/style.css"},
		 -background=>"/images/fondo.jpg", -BGCOLOR=>'FFFFFF' );
print "\n\n";

### debug #####################################################################
#my ($key_form);
#foreach $key_form (param()) { print("$key_form\=",param($key_form),"<br>\n"); }
###############################################################################

$dbh = DBI->connect("DBI:mysql:accesnot_sanchezm", "accesnot_sanman", "SanMan1100");

if (!defined $dbh) {
  print "No se puede conectar a la base de datos...\n";
  exit;
}

&print_file ("$path/_header.html");
if (!$clave) { print "<P class='big_font'>Clave no definida</P>\n"; }
else { &show_data; }
&print_file ("$path/_bottom.html");
print end_html;
exit;

###############################################################################

sub show_data {              # Busca registros y los imprime en una tabla

  my (@data, $where, $limit, $total_rows, $start_row, $end_row);
  my ($pg, $pg_fin, $count, $str, $link, @align, $param_items);
  my ($cliente);
  my ($criterio2) = param('criterio2');

  # primero buscamos si existe en la tabla de clientes
  $sth = $dbh->prepare("SELECT CLIENTE from clientes WHERE CLAVE='$clave'");
  $sth->execute; $cliente = $sth->fetchrow; $sth->finish;

  if ($cliente) { print "<CENTER><SPAN CLASS=small_font>$cliente</SPAN>\n"; }
  if (($criterio2) && ($criterio2 ne 'TODO')) {
    print "<BR><SPAN CLASS=small_font>";
    if ($criterio2 eq "FORMAL_MINUTA")    { print "Pendiente de minuta";     }
    if ($criterio2 eq "FORMAL_ESCRITURA") { print "Pendiente de escritura";  }
    if ($criterio2 eq "FORMALIZAR")       { print "Pendiente de formalizar"; }
    if ($criterio2 eq "FORMALIZAR_TRUE")  { print "Formalizadas";            }
    print "</SPAN>\n";
  }

  $where = "WHERE N_KARDEX <> ''";
  if ($clave ne $clave_geren) {
    $where .= " AND (CLAVE='$clave' OR CLAVE_PRINCIPAL='$clave' OR CLAVE_ESPECIAL='$clave' " .
                                   "OR CLAVE_ADICIONAL='$clave') ";
  }
  if (param('data')) {
      $where .= " AND " . param('criterio') . " LIKE '%" . param('data') . "%'";
  }
  if ($criterio2) { 
    if ($criterio2 eq "FORMAL_MINUTA")    { $where .= " AND FORMAL_MINUTA=0 ";    }
    if ($criterio2 eq "FORMAL_ESCRITURA") { $where .= " AND FORMAL_ESCRITURA=0 "; }
    if ($criterio2 eq "FORMALIZAR")       { $where .= " AND FORMALIZAR=0 ";       }
    if ($criterio2 eq "FORMALIZAR_TRUE")  { $where .= " AND FORMALIZAR=1 ";       }
  }

  # Primero tenemos que definir los parametros
  # pg - Pagina que queremos mostrar, # limit - para el select statement
  # order - columna para el orden (ORDER BY) y # norder - ASC o DESC

  $pg = param('pg');         if ($pg <= 0) { $pg=1 }
  $limit = param('limit');   if (!$limit)  { $limit=5 }
  if ($limit > 100) { $limit = 100; }
  if ($limit < 0)   { $limit = 5;  }

                             # Buscamos el total de los registros - COUNT(*)
  $sth = $dbh->prepare(
  "SELECT COUNT(*) FROM dato $where ORDER BY N_KARDEX");
  $sth->execute; ($total_rows) = $sth->fetchrow; $sth->finish;

  if ($total_rows == 0) {
    print "<P class='big_font'>No hay registros encontrados.</P>\n";
  }
  else {               # registros encontrados...

    $pg_fin = int($total_rows/$limit);
    if (($total_rows/$limit) != int($total_rows/$limit)) { $pg_fin++; }
    if ($pg > $pg_fin) { $pg = $pg_fin; }
    $start_row = ($pg-1)*$limit;
    $end_row = ($start_row+$limit);
    if ($end_row > $total_rows) { $end_row = $total_rows; }

    print "\n<TABLE ALIGN=center BORDER=0 CELLPADDING=2 CELLSPACING=0 WIDTH=100%><TR>";

    # agregamos los criterios para la busqueda
    $param_items = "&clave=$clave";
    if (param('data')) {
	$param_items .= "&criterio=" . param('criterio') . "&data=" . param('data'); 
    }
    if ($criterio2) {
      $param_items .= "&criterio2=" . $criterio2; 
    }
   
    if ($pg_fin > 1) {         # Links - siguentes paginas en el search if > 0
      print "<TD class='small_font'>";

      # Mostramos << si hay paginas anteriores
      if ($pg > 1) { print "<A HREF=$script_url?pg=", ($pg-1), "$param_items>&lt;&lt;</A>\n"; }
      else         { print "&lt;&lt; \n"; }

      if (((int(($pg-1)/10)*10)+1) > 1) { print "..."; }

      # Lista de 10 paginas agrupados 1..11 10..21 etc.
      for ($count=((int(($pg-1)/10)*10)+1); 
           $count<=((int(($pg-1)/10)*10)+11); $count++) {
        if ($count <= $pg_fin) {
          if ($count != $pg) { print "<A HREF=$script_url?pg=$count", "$param_items>$count</A>\n"; }
          else               { print "$count\n" }
        }
      }

      if (((int(($pg-1)/10)*10)+11) < $pg_fin) { print "..."; }

      # Mostramos >> si hay mas paginas.
      if ($pg < $pg_fin) { print "<A HREF=$script_url?pg=", ($pg+1), "$param_items>&gt;&gt;</A>\n"; }
      else               { print "&gt;&gt;\n"; }
      print "</TD>\n";
    }

    print "<TD ALIGN=right class='small_font'>Regstros ", ($start_row+1), "-", 
    $end_row, " de ", "$total_rows</TD></TR></TABLE>\n";

    print qq~
    <TABLE ALIGN="center" BORDER="0" CELLPADDING="2" CELLSPACING="1" WIDTH="100%">
    <TR>~;

    @align = ("left", "left", "left", "center", "center");
    $count = 0;
    foreach $str ("KARDEX", "CONTRATO", "CONTRATANTES", "ESCRITURA", "MINUTA") {
      print "<TD BGCOLOR=#AAAAAA CLASS=small_font ALIGN=", $align[$count], ">", 
            "<FONT COLOR=#000000>$str</FONT></TD>\n";
      $count++;
    }
    print "\n</TR>\n";

    if ($total_rows > 0) {
      $count = 0;
      $sth = $dbh->prepare(
      "SELECT * FROM dato $where ORDER BY N_KARDEX LIMIT $start_row, $limit");
      $sth->execute;
      while (@data = $sth->fetchrow) {
        $count++;
	$link = "detalle?clave=$clave&kardex=" . $data[3];
        if ($cliente) { $link .= "&especial=yes"; }
        print 
        "\n<TR><TD CLASS=small_font ALIGN=", $align[0], ">",
        "<A HREF=\"#\" onclick=\"window.open( ('", $link, "'), 'Kardex', ",
        "'menubar=no,scrollbars=yes,resizable=0,width=640,height=540');\">$data[3]</A></TD>\n",
        "<TD CLASS=small_font ALIGN=", $align[1], ">$data[5]</TD>\n",
        "<TD CLASS=small_font ALIGN=", $align[2], ">$data[6]</TD>\n",
        "<TD CLASS=small_font ALIGN=", $align[3], ">$data[8]</TD>\n",
        "<TD CLASS=small_font ALIGN=", $align[4], ">$data[9]</TD>\n",
        "</TR>\n";
      }

      if (($cliente) || ($total_rows > 1)) {

        print qq~
        <TR><TD BGCOLOR=#FFFFFF COLSPAN=5 CLASS=small_font><FONT COLOR=#000000>BUSCADOR</TD><TD>
        <TR><TD COLSPAN=4 CLASS=small_font>
        <form name="find" method="post" action="$script_url">
        <input type=hidden name="clave" value="$clave">
        <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=2 WIDTH=100%>
        <TR><TD CLASS=small_font>Buscar por:</TD>
        <TD CLASS=small_font><select name="criterio" size="1">
        <option value="N_KARDEX">No Kardex</option>
        <option value="CLIENTE">Cliente</option>
        <option value="CONTRATO">Contrato</option>
        <option value="OTORGANTES">Otorgantes</option>
        <option value="BENEFICIARIOS">Beneficiarios</option>
        <option value="N_ESCRITURA">No Escritura</option>
        <option value="N_MINUTA">No Minuta</option>
        <option value="F_ESCRITURA">Fecha de Escritura
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option>
        <option value="F_TITULO">Fecha de Titulo</option>
        <option value="N_TITULO">No de Titulo</option>
        </select>
        <input type="text" name="data" size="20">
        <input type="submit" name="find" value="Buscar"><BR>
        </TD></TR>~;
        if ($cliente) {
          print qq~
          <TR><TD>&nbsp;</TD><TD CLASS=small_font>
          <select name="criterio2" size="1" onChange="document.find.submit();">
          <option value="TODO">Mostrar Todos</option>
          ~;

          my (@values)  = ("FORMAL_MINUTA", "FORMAL_ESCRITURA", "FORMALIZAR", "FORMALIZAR_TRUE");
          my (@options) = ("Pendiente de minuta", "Pendiente de escritura", 
                           "Pendiente de formalizar", "Formalizadas");
          $count=0;
          foreach $str (@values) {
            print "<option value=\"", $values[$count], "\"";
            if ($criterio2 eq $values[$count]) { print " SELECTED" }
            print ">", $options[$count], "</option>\n";
            $count++;
          }
          print "</select></TD></TR>";
        }
        print qq~
        </TABLE>
        </FORM></TD>
        <TD class=small_font VALIGN=top ALIGN=CENTER><A HREF="$script_url?clave=$clave">Mostrar Todo</A></TD>
        </TR>~;

    }
 
    print "\n</TABLE>";

    $sth->finish;
    }
  }
}

###############################################################################

sub print_file {       # Abre el archivo especificado como argumento y
                       # lo imprime linea por linea.
    my($infile) = @_;
    open(INFILE, $infile) or return;
    while (<INFILE>) { print $_; }
    close (INFILE);
}