<?php

include_once("utiles.php");

date_default_timezone_set("America/Panama");
#error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_STRICT);

if (!$connection = connectDb()) {
    die("err db");
} else {
    mysqli_query($connection,"SET NAMES 'utf8'");
}
session_start();

$_SESSION["datab_orig"] = $_POST["datab_orig"];
$_SESSION["datab_dest"] = $_POST["datab_dest"];

$cDb_Ori = $_SESSION["datab_orig"];
$cDb_Des = $_SESSION["datab_dest"];

$Sql_ln = "SELECT * FROM `".$cDb_Ori."`.`productos` ";
//save_to_csv($connection, $Sql_ln, 'productos.csv');
save_sql_insert($connection, $Sql_ln, 'productos', 'productos.sql');
/*
zip_file('productos.zip','productos.sql');
if (file_exists('productos.sql')){
    unlink('productos.sql');
}
*/

$Sql_ln = "SELECT * FROM `".$cDb_Ori."`.`productos_det` WHERE `suc_id`=1 ";
//save_to_csv($connection, $Sql_ln, 'productos_det.csv');
save_sql_insert($connection, $Sql_ln, 'productos_det', 'productos_det.sql');
/*
zip_file('productos_det.zip','productos_det.sql');
if (file_exists('productos_det.sql')){
    unlink('productos_det.sql');
}
*/

mysqli_close($connection);

function save_mysql($pConn, $pDb_Ori, $PDb_Des, $pSql, $ptablename){
$recount = 0;
$SaveLog = 1;
#$tabProd = mysqli_query($connection, $Sql_ln);
$data = getRowAll02($pConn, $Sql_ln, $recount);

$Excl_Field = 'autoinc';
$sValue2 = jsonmysql_insert_result_str($data, $recount,  $ptablename, $pConn, $pDb_Ori, $PDb_Des, $SaveLog, $Excl_Field,1);
                                      //($tabla, $reg_p, $nombre, $connection1, $database, $database_dest, $pSaveLog, $Excl_Field, $On_Dlupl, $Replac_Blanks)
$str_sql = $str_sql . $sValue2;
unset($data);

$NameFile = $ptablename.'.sql';
$fp = fopen($NameFile, 'w');
fwrite($fp, $str_sql); 
}

function zip_file($pFileZip, $pPathFile){
    $zip = new ZipArchive;
    if ($zip->open($pFileZip, ZipArchive::CREATE) === TRUE)
    {
        // Add files to the zip file
        $zip->addFile($pPathFile);
     
        // All files are added, so close the zip file.
        $zip->close();
    }
}

function save_to_csv($pConn, $pSql, $pNameFile){
    $result = mysqli_query($pConn, $pSql);
    if (!$result){
        echo mysqli_error($pConn).chr(13);
    }
    $num_fields = mysqli_num_fields($result);
    $headers = array();
    for ($i = 0; $i < $num_fields; $i++) {
        $headers[] = mysqli_field_name($result , $i);
    }
    $fp = fopen($pNameFile, 'w');
    if ($fp && $result) {
        fputcsv($fp, $headers);
        fclose($fp);
    
        $fp = fopen($pNameFile, 'a');
        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $line = "";
            $comma = "";
            foreach($row as $value) {
                $line .= $comma . '"' . str_replace('"', '""', $value) . '"';
                $comma = ",";
            }
            $line .= chr(13);
            fwrite($fp, $line);
        }
        fclose($fp);
    }
     else {    
    }
   mysqli_free_result($result);    
}

function save_sql_insert($pConn, $pSql, $tablename, $pNameFile){
    $result = mysqli_query($pConn, $pSql);
    if (!$result){
        echo mysqli_error($pConn).chr(13);
    }
    $num_fields = mysqli_num_fields($result);
    $headers = array();
    for ($i = 0; $i < $num_fields; $i++) {
        $headers[] = mysqli_field_name($result , $i);
    }
    $sql_header = 'INSERT INTO '.$tablename.' (' . implode(',', $headers)  .') VALUES '. chr(13);;
    $fp = fopen($pNameFile, 'w');
    if ($fp && $result) {
        fwrite($fp, $sql_header);
        fclose($fp);
    
        $fp = fopen($pNameFile, 'a');
        $rowcount=mysqli_num_rows($result);
        $counter = 0;
        while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
            $counter++;
            $line = "";
            $comma = "";
            foreach($row as $value) {
                $line .= $comma . '"' . str_replace('"', '""', $value) . '"';
                $comma = ",";
            }
            if ($counter == $rowcount) {
                '(' . $line .= ') '. chr(13);
            }else {
                '(' . $line .= '), '. chr(13);
            }
            fwrite($fp, $line);
        }
        fclose($fp);
    }
     else {    
    }
   mysqli_free_result($result);    
}

function mysqli_field_name($result, $field_offset)
{
    $properties = mysqli_fetch_field_direct($result, $field_offset);
    return is_object($properties) ? $properties->name : null;
}

?>