<?php
 
/**
 * Points the script to the text file to be read and manipulated
 */



if(file_exists('./infusion-config.php'))
{
    include './infusion-config.php';}

$prodnumber=$_REQUEST['prod'];


#touch('./prods/'.$prodnumber.'.txt');
#touch('./prods/'.$prodnumber.'.php');

#define('CONFIG_FILE', realpath(__DIR__ . '/prods/'.$prodnumber.'.txt'));
#define('PHP_FILE', realpath(__DIR__ . '/prods/'.$prodnumber.'.php'));

 
 
 
 
/**
 * Parse the existing file
 */
 
// Get the text file's lines as an array
#$lines = file(CONFIG_FILE);
 
// Parse the elements out into a multi-dimensional array of the value tuples

 
 
 
 
 
/**
 * Update the text file on POST requests
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // assignment
  $new   = $_POST['new'];
  $lines = $_POST['lines'];
 
  // ensure we have an array
  if (!is_array($lines)) {
    $lines = array();
  }
 
  // Fail-safe to avoid wiping the file with a bad $_POST
  if (count($lines) < count($parsedLines) - 1) {
    header('HTTP/1.1 400 Bad Request');
    exit;
  }
 
 
 
  // filter lines to be removed; maintain keys
  $lines = array_filter($lines, function($line) {
    foreach ($line as $value) {
      if (strlen(trim($value))) {
        return true;
      }
    }
 
    return false;
  });
 
 
 
  // restore partially deleted lines
  array_walk($lines, function(&$line, $lineNumber) use ($parsedLines) {
    foreach ($line as $value) {
      if ( ! strlen(trim($value))) {
        $line = $parsedLines[$lineNumber];
        return;
      }
    }
  });
 
 
 
  // Add the new line if all fields have values
  $newLineExists = 3 == count(array_filter($new, function($value) {
    return !! strlen(trim($value));
  }));
 
  if ($newLineExists) {
    array_push($lines, $new);
  }
 
 
 
  // Write the new file contents
  $fileLines = array_map(
    function($values) {
      return sprintf("'%s' => '%s' , //%s\n", $values[0], $values[1], $values[2]);
    },
    $lines
  );
 

  // OPTIONAL: strip the last newline from file
  $fileLines[count($fileLines)-1] = rtrim($fileLines[count($fileLines)-1]);
 
  file_put_contents(CONFIG_FILE, $fileLines); 

//ek - write php file for thing to work
$fp = fopen($fn2,"w") or die ("Error opening file in write mode!"); 

$value = array_shift($parsedLines);
print_r ($value);

file_put_contents(PHP_FILE,"

<?php
    IF ( $"."cproditem == '1') { 

$"."arrACTIONSET   = array(

");

    file_put_contents(PHP_FILE,$fileLines,FILE_APPEND);


file_put_contents(PHP_FILE,"

);
}
?>

",FILE_APPEND);

    fclose($fp) or die ("Error closing file!");



  // Update the in-memory version of the lines (no need to re-read the file)
  $parsedLines = array_values($lines);

}

 
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>CBFuse For Infusionsoft</title>
<link href="//apps.ekaram.net/styles/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="//apps.ekaram.net/styles/css/bootstrap-responsive.css" rel="stylesheet">
<alink href="//apps.ekaram.net/styles/css/bureau.min.css" rel="stylesheet">

<script>
function IsEmpty(){
  if(document.forms['addprod'].prod.value == "")
  {
    alert("Please enter the Clickbank Product # Number you want to add");
    return false;
  }
    return true;
}
</script>

</head>
  <body>
<div class="page-header">
<center><h1>CBFuse<br>For Infusionsoft</h1></center>
</div>    
      <center> <table style="width:600px;" class="table table-striped table-hover table-bordered">
<thead> <tr>
  <center><h3>Your Clickbank Products</h3></center>
</tr>
</thead>

<?php

$dir = "./prods/";
$files = scandir($dir);
$q      =       (count($files)) ;
#echo $q;
if ($q >= 3)
    {



foreach (glob("./prods/*.php") as $productfiles)
{
 #   echo $productfiles;
    $slug = trim($productfiles, '.php');
    $slug = substr($slug, 7);
 
echo '<tr><td><h4><a href="./editpro.php?prod='.$slug.'">Clickbank Product #';
echo $slug;
echo '</a></h4></td>';

echo '<td><center>
<form  action="./editpro.php">
<input type="hidden" name="prod" value="'.$slug.'">
             <input type="submit" value="View / Edit" class="btn btn-success">


            </form>
';
echo '</center></td>';

echo '<td><center>
<form action="./delprod.php">
<input type="hidden" name="prod" value="'.$slug.'">
';
?>
             <input type="submit" value="Delete" class="btn btn-danger" onClick="return confirm('Are you sure you want to delete this product?');">
<?php
echo '
            </form>
';
echo '</center></td></tr>';



}

}
else
{
  echo"<code>No Products Found</code><br><h3>Please watch the following video to<br>setup your Infusionsoft Application and add your Clickbank products";
}
       ?>

       </table>
        <!-- New row -->
           
     
        <!-- Existing rows -->
        <hr>
        
<table style="width:600px;" class="table table-striped table-hover table-bordered">
  <tr>
 <td >

<?php
if ((empty($infusion_app)) || (empty($infusion_key)) || (empty($cbsecret_key)))
{

echo '
  <center><p><font color="red"><h4>Attention Required:</h4><p></font><h4><font color="red">Setup Incomplete</font></h4>
             <form action="./editinfusion.php">
              <input type="submit" value="Application Setup" class="btn btn-info">
            </form>
';

}
else
{ 
  echo '
<center><p><font color="white"><h4>.</h4><p></font><h4><font color="white">.</font></h4>
             <form action="./editinfusion.php">
              <input type="submit" value="Application Setup" class="btn btn-info">
            </form>

';
}
?>
<!--
<script language="javascript">
function toggle() {
        var ele = document.getElementById("toggleText");
        var text = document.getElementById("displayText");
        if(ele.style.display == "block") {
                ele.style.display = "none";
                text.innerHTML = "<img src=http://cdn.emiliokaram.com/images/plus.png border=0>";
        }
        else {
                ele.style.display = "block";
                text.innerHTML = "<img src=http://cdn.emiliokaram.com/images/minus.png border=0>";
        }
}
</script>
<a id="displayText" href="javascript:toggle();">
<button class="btn btn-info">Modify Infusionsoft Config</button></a>
<div id="toggleText" style="display: none">
  dfdfd
</div>
-->



            </td>


           
            <td ><center>
             <form  name="addprod" action="./editpro.php">


           
                                          <h5>Product Number : <input type="text" name="prod" style="width:30px;"placeholder="###" size="5">
</h5>   <input type="submit" value="Add New Product" onclick="return IsEmpty();" class="btn btn-success">

            </form>
</center>
            </td>

<!--            <td id="danger"><button id="danger" name="danger" class="danger btn btn-danger">Delete</button></td> -->
          </tr>

 
  </table>


 
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
    <script>

      $(function() {
        $('table td .danger').click(function(event) {

if (!confirm("You press this it delete row forever. You sure?"))
    {
        e.preventDefault();
        return;
    } 

          // let us do some work
          event.preventDefault();
          event.stopPropagation();
 
          // clear the row
          $(this).parents('tr').find('td input[name^="lines"]').val('');
 
          // submit the form
          $(this).parents('form').submit();
        });
      });




      $(function() {
        $('table td .editer').click(function(event) {


$("#pizza input").attr("readonly", false);

//if (!confirm("should i really submit"))
 //   {
  //      e.preventDefault();
   //     return;
  //  } 

          // let us do some work
          event.preventDefault();
          event.stopPropagation();
 
          // submit the form
    //      $(this).parents('form').submit();
        });
      });




      $(function() {
        $('table td .save').click(function(event) {



          // let us do some work
          event.preventDefault();
          event.stopPropagation();
 
          // submit the form
          $(this).parents('form').submit();
        });
      });

    </script>
<font color="gray"><?php
{
echo "App Name: ";
echo $infusion_app;

}
?>
</font>
  </body>
</html>
