<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once "labClass.php";
$con = new labClass();

$cID        = $_GET['cID'] ?? null; 
$type       = $_GET['type'] ?? 'both'; // deposit | withdraw | both
$startDate  = $_GET['start_date'] ?? null;
$endDate    = $_GET['end_date'] ?? null;

// --- Prepare customer list for datalist ---
$customers = $con->getCus()->fetchAll(PDO::FETCH_ASSOC);

// --- Determine which to use: phone or customer ID ---
 

// --- Opening balance ---
$openingDeposits = 0;
$openingWithdrawals = 0;
$openingBalance = 0;

if (!empty($cID)) {
    $openDepo = $con->genOpeningDepo($cID, $startDate);
    $openingDeposits = $openDepo ? ($openDepo->fetchColumn() ?? 0) : 0;

    $openWith = $con->genOpeningWith($cID, $startDate);
    $openingWithdrawals = $openWith ? ($openWith->fetchColumn() ?? 0) : 0;

    $openingBalance = $openingDeposits - $openingWithdrawals;
}

// --- Main transactions ---
$transactions = [];
if (!empty($cID)) {
    $stmt = $con->genBothTrans($type, $startDate, $endDate, $cID);
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// --- Compute running balance ---
$runningBalance = $openingBalance;
foreach ($transactions as &$txn) {
    $runningBalance += $txn['amount'];
    $txn['balance'] = $runningBalance;
}
unset($txn);
$closingBalance = $runningBalance;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Customer Statement</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.custom-blue-border, .custom-blue-border th, .custom-blue-border td {
  border: 1px solid #007bff !important;
}
.deposit { color: green; font-weight: 600; }
.withdraw { color: red; font-weight: 600; }
.negative-balance { color: red; font-weight: bold; }
.table-warning td, .table-info td { font-weight: bold; }
</style>
</head>
<body class="p-4">

<h3 class="mb-3 text-primary">Customer Statement</h3>

<div class="container mb-3">
  <div class="row g-2 align-items-end">

    <!-- Search by Customer Name -->
    <div class="col-md-3">
      <label class="form-label mb-0">Search by Customer Name</label>
      <input list="customerList" name="cID" id="cID" class="form-control"
             placeholder="Select customer..." value="<?= htmlspecialchars($cID ?? '') ?>">
      <datalist id="customerList">
        <?php foreach ($customers as $c): ?>
          <option value="<?= htmlspecialchars($c['recID']) ?>"><?= htmlspecialchars($c['cname']) ?></option>
        <?php endforeach; ?>
      </datalist>
    </div>

    <!-- Search by Phone Number -->
    <div class="col-md-3">
      <label class="form-label mb-0">Search by Phone Number</label>
      <input list="phoneList" name="phone" id="phone" class="form-control"
             placeholder="Select phone number..." value="<?= htmlspecialchars($phone ?? '') ?>">
      <datalist id="phoneList">
        <?php foreach ($customers as $c): ?>
          <option value="<?= htmlspecialchars($c['recID']) ?>"><?= htmlspecialchars($c['phone']) ?></option>
        <?php endforeach; ?>
      </datalist>
    </div>

    <!-- Transaction type -->
    <div class="col-md-2">
      <label class="form-label mb-0">Transaction Type</label>
      <select name="type" class="form-select">
        <option value="both" <?= $type === 'both' ? 'selected' : '' ?>>Both</option>
        <option value="deposit" <?= $type === 'deposit' ? 'selected' : '' ?>>Deposit</option>
        <option value="withdraw" <?= $type === 'withdraw' ? 'selected' : '' ?>>Withdraw</option>
      </select>
    </div>

    <!-- Optional start date -->
    <div class="col-md-2">
      <label class="form-label mb-0">Start Date (optional)</label>
      <input type="date" name="start_date" value="<?= htmlspecialchars($startDate ?? '') ?>" class="form-control">
    </div>

    <!-- Optional end date -->
    <div class="col-md-2">
      <label class="form-label mb-0">End Date (optional)</label>
      <input type="date" name="end_date" value="<?= htmlspecialchars($endDate ?? '') ?>" class="form-control">
    </div>

    <!-- Generate button -->
    <div class="col-md-2 d-flex align-items-end">
      <button type="button" class="btn btn-primary w-100"
        onclick="
          var cID = $('#cID').val().trim();
          var phone = $('#phone').val().trim();
          var type = $('select[name=type]').val();
          var start_date = $('input[name=start_date]').val();
          var end_date = $('input[name=end_date]').val();

          // If phone is filled, ignore cID
          if (phone !== '') cID = phone;

          $.get('cusstatementBdt.php', {
            cID: cID,
            type: type,
            start_date: start_date,
            end_date: end_date
          }, function(data) {
            $('#dpl').html(data).show();
          });
        ">
        Generate
      </button>
    </div>

<div class="col-md-2 d-flex align-items-end">
<button type="submit" class="btn btn-primary" value="Print" style="width:30%; height:40px;" onclick="printPageArea();">Print </button>
  </div>
  </div
</div>

<div class="container mb-3" id="dpl">
<?php if (!empty($cID)): ?>
<table class="table table-bordered custom-blue-border">
  <thead class="table-light">
    <tr>
      <th>Date</th>
      <th>Description</th>
      <th>Deposit</th>
      <th>Withdraw</th>
      <th>Balance</th>
    </tr>
  </thead>
  <tbody>
    <tr class="table-warning">
      <td colspan="4" class="text-end"><strong>Opening Balance:</strong></td>
      <td><strong><?= number_format($openingBalance, 2) ?></strong></td>
    </tr>

    <?php if (empty($transactions)): ?>
      <tr><td colspan="5" class="text-center text-muted">No transactions found.</td></tr>
    <?php else: ?>
      <?php foreach ($transactions as $txn): ?>
        <tr>
          <td><?= htmlspecialchars($txn['tdate']) ?></td>
          <td><?= htmlspecialchars($txn['description']) ?></td>
          <td class="deposit"><?= $txn['amount'] > 0 ? number_format($txn['amount'], 2) : '' ?></td>
          <td class="withdraw"><?= $txn['amount'] < 0 ? number_format(abs($txn['amount']), 2) : '' ?></td>
          <td class="<?= $txn['balance'] < 0 ? 'negative-balance' : '' ?>">
            <?= number_format($txn['balance'], 2) ?>
          </td>
        </tr>
      <?php endforeach; ?>
    <?php endif; ?>

    <tr class="table-info">
      <td colspan="4" class="text-end"><strong>Closing Balance:</strong></td>
      <td><strong><?= number_format($closingBalance, 2) ?></strong></td>
    </tr>
  </tbody>
</table>
<?php else: ?>
  <div class="alert alert-info">Please select a customer name or phone number to view their statement.</div>
<?php endif; ?>
</div>
</body>
</html>
<script type="text/javascript">
  function printPageArea(){
    var printContent = document.getElementById('dpl').innerHTML;
    var originalContent = document.body.innerHTML;
    document.body.innerHTML = printContent;
    window.print();
    document.body.innerHTML = originalContent;
}

</script>
