<?php

 session_start();
  $rut=$_SESSION['rut'];
  $cliente=$_SESSION['cliente'];





$cumple_eliminar=$_REQUEST['cumple_eliminar'];

$caja_id_eliminar=$_REQUEST['caja_id_eliminar'];


include '../../conexion/conn.php';

if($cumple_eliminar=='SI'){
  $rs = mysql_query("SELECT * FROM cal_cajas where caja_id='$caja_id_eliminar' or caja_madre='$caja_id_eliminar'");

          while($row = mysql_fetch_array($rs)){

            $rs_caja_hijas = mysql_query("SELECT * FROM cal_cajas where caja_id='$caja_id_eliminar'");

            if($row_caja_hijas = mysql_fetch_array($rs_caja_hijas)){
              $caja_madre=$row_caja_hijas['caja_madre'];
              $caja_id_real2=$row_caja_hijas['caja_id'];
              if($caja_madre==""){
                $caja_id_real=$caja_id_real2;
              }else{
                $caja_id_real=$caja_madre;
              }
            }
            $rs_caja_hijas = mysql_query("SELECT COUNT(*) as cant_caja_hijas FROM cal_cajas where caja_id='$caja_id_real' or caja_madre='$caja_id_real'");

            if($row_caja_hijas = mysql_fetch_array($rs_caja_hijas)){
              $cant_caja_hijas=$row_caja_hijas['cant_caja_hijas']-1;
              if($cant_caja_hijas=='1'){
                $cant_caja_hijas=0;
              }
            }

            $caja_id_eliminar2=$row['caja_id'];

            $sql6 = "DELETE FROM cal_cajas_det WHERE caja_id='$caja_id_eliminar2'";
            $result6 = @mysql_query($sql6);

            $sql7 = "DELETE FROM cal_cajas_fotos WHERE caja_id='$caja_id_eliminar2'";
            $result7 = @mysql_query($sql7);

            $sql8 = "DELETE FROM cal_caja_causal WHERE caja_id='$caja_id_eliminar2'";
            $result8 = @mysql_query($sql8);

            $sql9 = "DELETE FROM cal_caja_peso_fijo WHERE caja_id='$caja_id_eliminar2'";
            $result9 = @mysql_query($sql9);

            $sql999 = "DELETE FROM cal_caja_firmeza WHERE caja_id='$caja_id_eliminar2'";
            $result999 = @mysql_query($sql999);

            $sql93 = "DELETE FROM cal_caja_peso_fruto WHERE caja_id='$caja_id_eliminar2'";
            $result93 = @mysql_query($sql93);

            $sql9 = "DELETE FROM cal_cajas WHERE caja_id='$caja_id_eliminar2'";
            $result9 = @mysql_query($sql9);

            $resultado=mysql_query("UPDATE cal_cajas 
            SET cant_caja_hijas='$cant_caja_hijas'
            
            WHERE caja_id='$caja_id_real'");




          }
}








 


echo json_encode(array('success'=>true));

?>