<?php
include("../classes/manager.class.php");
ini_set('display_errors', 1);
error_reporting(E_ALL);
$m = new Manager();

if (!isset($_SESSION['sess_userid'])) { header("Location: " . PROJECT_ADMIN_URL); exit(); }

$output = "";

// --- Filters (GET) ---
$from_date   = isset($_GET['from_date']) ? trim($_GET['from_date']) : "";
$to_date     = isset($_GET['to_date'])   ? trim($_GET['to_date'])   : "";
$supplier_id = isset($_GET['supplier_id']) ? (int)$_GET['supplier_id'] : 0;

// Build filter SQL (safe)
$filter = " WHERE 1=1 ";
if ($supplier_id > 0) {
    $filter .= " AND supplier_id = '$supplier_id' ";
}
if ($from_date !== "" && $to_date !== "") {
    // inclusive range
    $filter .= " AND date BETWEEN '".$from_date."' AND '".$to_date."' ";
} elseif ($from_date !== "") {
    $filter .= " AND date >= '".$from_date."' ";
} elseif ($to_date !== "") {
    $filter .= " AND date <= '".$to_date."' ";
}

// Pull suppliers for dropdown + a quick map for names
$supers = SupplierSetup::GetSupplierSetupList(" WHERE status='active'");
$supplierMap = [];
if ($supers) {
    foreach ($supers as $s) $supplierMap[$s->id] = $s->name;
}

// Fetch purchases
$purchases = PurchaseSetup::GetPurchaseList($filter);

// message flashes
if (isset($_GET['sucess'])) {
    $output .= "<div id='card-alert' class='card green lighten-5'><div class='card-content green-text'><p>Successfully updated!</p></div></div>";
}
if (isset($_GET['error'])) {
    $output .= "<div id='card-alert' class='card orange lighten-5'><div class='card-content orange-text'><p>WARNING: Error occurred!</p></div></div>";
}

// Mark purchase as Paid (old quick button still supported)
if (isset($_GET['paid']) && ctype_digit($_GET['paid'])) {
    $purchaseId = (int)$_GET['paid'];
    $data = [
        'status' => 'Paid',
    ];
    PurchaseSetup::UpdatePurchase($purchaseId, $data);

    // Preserve filters when redirecting, if you like:
    $qs = [];
    if ($from_date !== "") $qs[] = 'from_date='.urlencode($from_date);
    if ($to_date !== "")   $qs[] = 'to_date='.urlencode($to_date);
    if ($supplier_id > 0)  $qs[] = 'supplier_id='.$supplier_id;
    $qs[] = 'sucess';

    header("Location: purchase_setup.php?".implode('&', $qs));
    exit();
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <style>
        .right-align { text-align:right; }
        .filters .input-field { margin-top: 0; }
        .table-datatables .dataTables_wrapper { overflow-x:auto; }
    </style>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->

<div id="container">
<?php include('includes/inc_top.php'); ?>

<div class="row">
  <div class="col s12 m12">
    <div class="">
      <h3>Purchase List</h3>
    </div>
    <hr>

    <div class="row">
      <div class="col s12">
        <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;" href="purchase_create.php">
          Add Purchase <i class="mdi-content-add-box" style="font-size:12px;"></i>
        </a>
      </div>
    </div>

    <?php echo $output; ?>

    <!-- Filters -->
    <div class="card-panel">
      <form method="get" action="" class="filters">
        <div class="row">
          <div class="input-field col s12 m3">
            <input type="date" id="from_date" name="from_date" value="<?php echo htmlspecialchars($from_date); ?>">
            <label class="active" for="from_date">From Date</label>
          </div>
          <div class="input-field col s12 m3">
            <input type="date" id="to_date" name="to_date" value="<?php echo htmlspecialchars($to_date); ?>">
            <label class="active" for="to_date">To Date</label>
          </div>
          <div class="input-field col s12 m4">
            <select name="supplier_id" id="supplier_id">
              <option value="0" <?php echo ($supplier_id==0?'selected':''); ?>>All Suppliers</option>
              <?php
              if ($supers) {
                  foreach ($supers as $s) {
                      $sel = ($supplier_id == (int)$s->id) ? 'selected' : '';
                      echo "<option value='{$s->id}' $sel>".htmlspecialchars($s->name)."</option>";
                  }
              }
              ?>
            </select>
            <label for="supplier_id">Supplier</label>
          </div>
          <div class="input-field col s12 m2">
            <button type="submit" class="btn waves-effect waves-light" style="width:100%;">Filter</button>
          </div>
        </div>
      </form>
    </div>

    <!-- Results count -->
    <div class="row">
      <div class="col s12">
        <p><strong>Results:</strong> <?php echo ($purchases ? count($purchases) : 0); ?></p>
      </div>
    </div>

    <!-- Table -->
    <div class="table-datatables">
      <table id="data-table-simple" class="responsive-table display">
        <thead>
          <tr>
            <th>Action</th>
            <th>Date</th>
            <th>Supplier</th>
            <th>PO #</th>
            <th class="right-align">Total Amount</th>
            <th>Status</th>
            <th>Created</th>
            <th>No. of Days</th>
          </tr>
        </thead>
        <tfoot>
          <tr>
            <th>Action</th>
            <th>Date</th>
            <th>Supplier</th>
            <th>PO #</th>
            <th class="right-align">Total Amount</th>
            <th>Status</th>
            <th>Created</th>
            <th>No. of Days</th>
          </tr>
        </tfoot>
        <tbody>
          <?php
          if ($purchases) {
              foreach ($purchases as $p) {
                  $supplierName = isset($supplierMap[$p->supplier_id]) ? $supplierMap[$p->supplier_id] : null;
                  if ($supplierName === null) {
                      $srow = SupplierSetup::GetSupplierSetupById($p->supplier_id);
                      $supplierName = $srow ? $srow->name : '#'.$p->supplier_id;
                  }

                  // DAYS SINCE PURCHASE (from $p->date to today)
                  $daysSince = '';
                  if (!empty($p->date)) {
                      try {
                          $purchaseDt = new DateTime(substr($p->date, 0, 10)); // ignore time part if any
                          $todayDt    = new DateTime('today');
                          $daysSince  = max(0, (int)$purchaseDt->diff($todayDt)->format('%a'));
                      } catch (Exception $e) {
                          $daysSince = '';
                      }
                  }

                  $isPaid = isset($p->status) && strtolower(trim($p->status)) === 'paid';
                  ?>
                  <tr>
                    <td>
                      <?php if (!$isPaid): ?>
                        <!-- View -->
                        <a href="purchase_create.php?edit&id=<?php echo (int)$p->id; ?>&v" title="View">
                          <span class="mini-stat-icon pink" style="width:20px;height:20px;font-size:12px;line-height:20px;">
                            <i class="mdi-action-description"></i>
                          </span>
                        </a>

                        <!-- Edit -->
                        <a href="purchase_create.php?edit&id=<?php echo (int)$p->id; ?>" title="Edit">
                          <span class="mini-stat-icon orange" style="width:20px;height:20px;font-size:12px;line-height:20px;">
                            <i class="mdi-image-edit"></i>
                          </span>
                        </a>

                        <!-- NEW: Payment button (same idea as invoice payment) -->
                        <a href="purpayment_create.php?add&ref=<?php echo (int)$p->id; ?>" title="Payment">
                          <span
                            class="mini-stat-icon green darken-2"
                            style="width:60px; height:20px; border-radius:5%; font-size:12px; line-height:20px; display:inline-block; text-align:center; margin-left:5px;">
                            Payment
                          </span>
                        </a>

                        <!-- Existing quick 'Paid' status button (optional to keep) -->
                        <a style="margin-left:30px; display:block; cursor:pointer; font-size:10px; padding:1px;" title="Paid">
                          <span
                            class="btn-warning-paid mini-stat-icon cyan darken-2"
                            data-id="<?php echo (int)$p->id; ?>"
                            style="width:50px; height:20px; border-radius:5%; font-size:12px; line-height:20px; display:inline-block; text-align:center;">
                            Paid
                          </span>
                        </a>
                      <?php else: ?>
                        <!-- Already paid -->
                        <span class="mini-stat-icon green" style="width:auto;height:20px;font-size:12px;line-height:20px;padding:0 8px;border-radius:4px;">
                          Paid
                        </span>
                      <?php endif; ?>
                    </td>
                    <td><?php echo htmlspecialchars($p->date); ?></td>
                    <td><?php echo htmlspecialchars($supplierName); ?></td>
                    <td><?php echo htmlspecialchars($p->po_number); ?></td>
                    <td class="right-align"><?php echo number_format((float)$p->total_amount, 2); ?></td>
                    <td><?php echo htmlspecialchars($p->status); ?></td>
                    <td><?php echo htmlspecialchars($p->datetime); ?></td>
                    <td>
                      <?php
                        if (!$isPaid) {
                            echo ($daysSince === '' ? '' : (int)$daysSince);
                        }
                      ?>
                    </td>
                  </tr>
                  <?php
              }
          }
          ?>
        </tbody>
      </table>
    </div>

  </div>
</div>
</div>

<?php include('includes/inc_footer.php'); ?>
<?php include('includes/inc_js.php'); ?>
<script>
// Guard Materialize init (Rocket Loader safe)
(function initM(){
  function go(){
    if (window.M && M.FormSelect) { try { M.FormSelect.init(document.querySelectorAll('select')); } catch(e) {} }
  }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', go);
  } else { go(); }
})();

// One global delegated handler is enough
$(document).on('click', '.btn-warning-paid', function () {
  var id = $(this).data('id');
  if (!id) return;

  swal({
    title: "Are you sure?",
    text: "This purchase will be marked as Paid.",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes',
    cancelButtonText: 'No',
    closeOnConfirm: false
  }, function () {
    swal("Successful!", "Status set to Paid.", "success");
    window.location.href = 'purchase_setup.php?paid=' + encodeURIComponent(id)
      <?php
        $filterQs = [];
        if ($from_date !== "") $filterQs[] = "from_date=".urlencode($from_date);
        if ($to_date !== "")   $filterQs[] = "to_date=".urlencode($to_date);
        if ($supplier_id > 0)  $filterQs[] = "supplier_id=".$supplier_id;
        echo (!empty($filterQs) ? "+'&".implode("&", $filterQs)."'" : "");
      ?>;
  });
});

</script>
</body>
</html>
