<?php
  include 'connect.php'; // include database connection file
  include 'header.php'; // include header file
  include 'nav.php'; // include navigation menu file
  session_start();
  if(!isset($_SESSION['emailadd'])){
     header("Location: index.php");
  }

  $conn = mysqli_connect($servername, $username, $password, $dbname);
  if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
  }

  // Retrieve list of available account numbers
  $query = "SELECT accno, accholder FROM bankacc";
  $result = mysqli_query($conn, $query);
  $accounts = array();
  while ($row = mysqli_fetch_assoc($result)) {
    $accounts[] = $row['accno'];
  }
?>
<main>
  <link rel="stylesheet" type="text/css" href="style.css">
  <style>
    /* Define table styles */
    table {
      border-collapse: collapse;
      width: 100%;
    }

    th, td {
      text-align: left;
      padding: 8px;
    }

    th {
      background-color: #4CAF50;
      color: white;
    }

    tr:nth-child(even) {background-color: #f2f2f2;}

    /* Define "Add Data" button styles */
    .add-data-button {
      background-color: #4CAF50;
      color: white;
      border: none;
      padding: 10px;
      text-align: center;
      text-decoration: none;
      display: inline-block;
      font-size: 16px;
      margin: 4px 2px;
      cursor: pointer;
      border-radius: 4px;
    }

    .add-data-button:hover {
      background-color: #3e8e41;
    }
  </style>

  <h2>Bank Statement</h2>

  <form method="post">
    <div>
      <label for="accno">Account Number:</label>
      <select id="accno" name="accno">
            <?php
        // Retrieve list of available account numbers
            $query = "SELECT accno, accholder FROM bankacc";
            $result = mysqli_query($conn, $query);
            while ($row = mysqli_fetch_assoc($result)) {
              echo "<option value='" . $row['accno'] . "'>" . $row['accholder'] . "</option>";
            }
            ?>
      </select>

      <label for="month">Month:</label>
      <select id="month" name="month">
        <?php for ($m = 1; $m <= 12; $m++): ?>
          <option value="<?php echo $m; ?>"><?php echo date('F', mktime(0, 0, 0, $m, 1)); ?></option>
        <?php endfor; ?>
      </select>

      <label for="year">Year:</label>
      <select id="year" name="year">
        <?php for ($y = date('Y'); $y >= 2000; $y--): ?>
          <option value="<?php echo $y; ?>"><?php echo $y; ?></option>
        <?php endfor; ?>
      </select>

      <button type="submit">View Statement</button>
    </div>
  </form>


  <?php if(isset($_POST['accno'])): // if form submitted ?>
    <?php
    // Get selected account number and period from the form
    $selected_accno = $_POST['accno'];
    $selected_month = $_POST['month'];
    $selected_year = $_POST['year'];

    // Calculate the start and end dates of the selected month based on the server's timezone
    $dt_start = new DateTime("$selected_year-$selected_month-01", new DateTimeZone('UTC'));
    $dt_start->setTimezone(new DateTimeZone(date_default_timezone_get()));
    $start_of_month = $dt_start->format('Y-m-d');
    $dt_end = new DateTime("$selected_year-$selected_month-01 +1 month -1 day", new DateTimeZone('UTC'));
    $dt_end->setTimezone(new DateTimeZone(date_default_timezone_get()));
    $end_of_month = $dt_end->format('Y-m-d');

    // Retrieve transactions for the selected account number and period
    $query = "SELECT trndate, docno, amount, remark, recfrm FROM bank_trn WHERE accno = '$selected_accno' AND trndate >= '$start_of_month' AND trndate <= '$end_of_month' ORDER BY trndate";
    $result = mysqli_query($conn, $query);

    // Set initial balance to 0
    $balance = 0;

    // Calculate bring forward balance
    $query1 = "SELECT SUM(amount) AS total_amount FROM bank_trn WHERE accno = '$selected_accno' AND trndate < '$selected_year-$selected_month-01'";
    $result1 = mysqli_query($conn, $query1);
    $row1 = mysqli_fetch_assoc($result1);
    $total_amount = $row1['total_amount'] ?: 0;

    $bf = $total_amount;
    $balance = $bf;

?>

<h2>Bank Statement for Account Number <?php echo $selected_accno; ?> for <?php echo date('F Y', strtotime("$selected_year-$selected_month-01")); ?></h2>

<table>
  <tr>
    <th>Date</th>
    <th>Document No</th>
    <th>Remark</th>
    <th>Receipt From/Payment To</th>
    <th>Money In</th>
    <th>Money Out</th>
    <th>Balance</th>
  </tr>

  <tr>
    <td>B/F Balance</td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td><?php echo number_format($bf, 2); ?></td>
  </tr>

  <?php
    $total_money_in = 0;
    $total_money_out = 0;
    while ($row = mysqli_fetch_assoc($result)):
      $money_in = max(0, $row['amount']);
      $money_out = max(0, -$row['amount']);
      $total_money_in += $money_in;
      $total_money_out += $money_out;
  ?>
    <tr>
      <td><?php echo $row['trndate']; ?></td>
      <td><?php echo $row['docno']; ?></td>
      <td><?php echo $row['remark']; ?></td>
      <td><?php echo $row['recfrm']; ?></td>
      <td><?php echo number_format($money_in, 2); ?></td>
      <td><?php echo number_format($money_out, 2); ?></td>
      <td><?php $balance += $row['amount']; echo number_format($balance, 2); ?></td>
    </tr>
  <?php endwhile; ?>

  <tr>
    <th>Total</th>
    <td></td>
    <td></td>
    <td></td>
    <td><?php echo number_format($total_money_in, 2); ?></td>
    <td><?php echo number_format($total_money_out, 2); ?></td>
    <td></td>
  </tr>

</table>

  <?php endif; ?>
</main>
<?php
  // Close database connection
  mysqli_close($conn);
?>