<?php
 
/**
 * Points the script to the text file to be read and manipulated
 */
define('CONFIG_FILE', realpath(__DIR__ . '/bill.txt'));
define('PHP_FILE', realpath(__DIR__ . '/bill.php'));
$fn2 ="bill.php";
$fp = fopen($fn2,"w") or die ("Error opening file in write mode!"); 
 
 
 
 
/**
 * 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
$parsedLines = array_map(
  function($line) {
    preg_match('#\A\'([^\']+)\' => \'([^\']+)\' , //(.+)\Z#', $line, $matches);
 
    array_shift($matches); // shift the original match (the whole line) off the stack
 
    return $matches;
  },
  $lines
);
 
 
 
 
 
 
/**
 * 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

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

file_put_contents(PHP_FILE,"

<?php
$"."bill=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>Edit and Save Text File With PHP</title>
  <link href="//apps.ekaram.net/styles/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
  <body>
 
    <form method="post">
      <table>
 
        <!-- New row -->
        <tfoot>
          <tr>
            <td colspan="4">Add More:</td>
          </tr>
          <tr>
            <?php for ($i=0; $i<3; $i++) { ?>
              <td><input name="new[<?php echo $valueNumber; ?>]"></td>
            <?php } ?>
            <td></td>
          </tr>
          <tr>
            <td colspan="4"><input type="submit" value="Add Row"></td>
          </tr>
        </tfoot>
 
        <!-- Existing rows -->
        <?php foreach ($parsedLines as $lineNumber => $line) { ?>
          <tr>
            <?php foreach ($line as $valueNumber => $value) { ?>
              <td>
                <input name="lines[<?php echo $lineNumber; ?>][<?php echo $valueNumber; ?>]" value="<?php echo $value; ?>">
              </td>
            <?php } ?>
            <td><button class="btn btn-danger">Delete</button></td>
          </tr>
        <?php } ?>
      </table>
    </form>
 
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
    <script>
      $(function() {
        $('tbody button').click(function(event) {
 
          // 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();
        });
      });
    </script>
  </body>
</html>
