<?php
session_start();
require_once ("../conexion.php");
require_once('../include/sesiones.php');

if (!empty($_POST['fam_nombre']))
{
    $fam_nombre=mb_strtoupper(mysqli_real_escape_string($con, $_POST['fam_nombre']));
    $can1=mysqli_query($con,"SELECT * FROM familias where fam_nombre='$fam_nombre' AND empresa='$empresa'") or die(mysqli_error($con)); 
    $result = mysqli_num_rows($can1);
    if($result == 0)
    {
        $can=mysqli_query($con,"SELECT MAX(fam_id)as fam_id FROM familias") or die(mysqli_error($con)); 
        $dato=mysqli_fetch_array($can); 
        $fam_id=$dato['fam_id']+1;

        $nameimagen = $_FILES['imagen']['name'];
        $tmpimagen = $_FILES['imagen']['tmp_name'];
        $extimagen = pathinfo($nameimagen);
        $ext = array("","jpg","jpeg","png","jfif","gif","tif","tiff");
        $urlnueva = "../img/categorias/".$fam_id.".jpg";
        if(is_uploaded_file($tmpimagen))
        {
           if(array_search($extimagen['extension'],$ext))
            {
                copy($tmpimagen, $urlnueva);
            }
            else 
            {
               echo '<div class="alert alert-danger alert-dismissable">
                      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                      <strong>La imagen no se guardo! </strong> Solo se permiten imágenes con formato  jpg.
                    </div>';
            }
        }
        
        $sql="INSERT into familias (fam_id,fam_nombre,empresa,fam_destacado) 
              VALUES ('$fam_id','$fam_nombre','$empresa','no')";

        $query_new_insert = mysqli_query($con,$sql);
        if ($query_new_insert)
        {
            echo '<div class="alert alert-info alert-dismissable">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <strong>La Categoria ha sido ingresado satisfactoriamente. </strong>
                </div>';
        } 
        else
        {
             echo '<div class="alert alert-danger alert-dismissable">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <strong>Lo siento algo ha salido mal intenta nuevamente. </strong>
                </div>';
        }
    }   
    else 
    {
         echo '<div class="alert alert-danger alert-dismissable">
                  <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                  <strong>Nombre no disponible. </strong>
                </div>';
    }
}
?>