<?php
session_start();
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (!isset($_SESSION['aW1iZXN0cmEuY29tLm15']) || $_SESSION['aW1iZXN0cmEuY29tLm15'] != $key) {
    header("location:".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']);
    exit;
}

include "_header2.php";
include "_navtop.php";
include "_navside.php";
require "conn.php";
?>
<style>
.action-icon { cursor:pointer; margin-right:10px; }
.table-responsive { overflow-x:auto; }
.item-row input, .item-row select { width: 100%; }

.custom-fieldset {
  border: 1px solid #ccc;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  background: #fafafa;
}
.custom-legend {
  font-size: 15px;
  font-weight: 600;
  color: #1a2226;
  padding: 0 10px;
  width: auto;
}
</style>


<div id="page-wrapper">
<div id="page-inner">
    <div class="row">
        <div class="col-md-12">
            <h2>Package List</h2>
        </div>
    </div>
    <hr />

    <form method="get" class="mb-3">
        <div style="display:flex; gap:20px; flex-wrap:wrap; align-items:flex-end;">
            <div class="form-group mb-2">
                <label>Package Name :</label>
                <input type="text" name="name" value="<?= htmlspecialchars($_GET['name'] ?? '') ?>" placeholder="Search package..." class="form-control" style="max-width:200px;">
            </div>
            <div class="form-group mb-2">
                <button type="submit" class="btn btn-primary">Search</button>
                <button type="button" class="btn btn-success" data-toggle="modal" data-target="#packageModal" onclick="openAddModal()">+ Add Package</button>
            </div>
        </div>
    </form>

    <div class="panel panel-default">
        <div class="panel-heading">List of All Packages</div>
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table table-striped table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th style="display:block; text-align: right;">Price (RM)</th>
                            <th>Qty Set</th>
                            <th style="display:block; text-align: right;">Direct Sponsor (RM)</th>
                            <th>Commission Level</th>
                            <th>Items</th>
                            <th>Package Profit</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
<?php
$c = 1;
$keyword = mysqli_real_escape_string($con, $_GET['name'] ?? '');
$q = $keyword ? "WHERE name LIKE '%$keyword%'" : '';
$res = mysqli_query($con, "SELECT * FROM packages $q ORDER BY id DESC");

while ($row = mysqli_fetch_assoc($res)) {
    $items = json_decode($row['items'], true) ?: [];

    $defaultImg = "uploads/products/no_img.png";

    $itemHtml = '';
    $totalCost = 0.0;
    $totalProfit = 0.0;

    foreach ($items as $it) {
        $product_id = intval($it['product_id']);
        $qty        = intval($it['qty']);

        $sql = "SELECT * FROM products WHERE id = $product_id LIMIT 1";
        $prodRes = mysqli_query($con, $sql);
        $prod = $prodRes ? mysqli_fetch_assoc($prodRes) : null;
        if (!$prod) continue;

        $productName   = htmlspecialchars($prod['product_name'] ?? 'Unknown', ENT_QUOTES);
        $sku           = htmlspecialchars($prod['sku'] ?? '-', ENT_QUOTES);
        $imgFile       = trim($prod['img'] ?? '');
        $price         = floatval($prod['price'] ?? 0);
        $cost          = floatval($prod['cost_price'] ?? 0);
        $discountTypeP = $prod['discount_type'] ?? 'NONE';
        $discountValueP= floatval($prod['discount_value'] ?? 0);
        $description   = htmlspecialchars($prod['description'] ?? '', ENT_QUOTES);

        if ($discountTypeP === 'PERCENT') {
            $discountAmt = ($price * $discountValueP / 100.0);
        } elseif ($discountTypeP === 'FIXED') {
            $discountAmt = $discountValueP;
        } else {
            $discountAmt = 0.0;
        }

        if (isset($it['cost_price'])) $cost = floatval($it['cost_price']);
        if (isset($it['price'])) $price = floatval($it['price']);
        if (isset($it['discount_amount'])) {
            $discountAmt = floatval($it['discount_amount']);
            if (!empty($it['discount_type'])) $discountTypeP = $it['discount_type'];
        }

        $imgPath = $imgFile ? "uploads/products/" . rawurlencode($imgFile) : "assets2/ico/tls2u.png";
        

        $totalCost += ($cost * $qty);
        $productProfit = ($price - $cost - $discountAmt) * $qty;
        $totalProfit += $productProfit;

        $costFmt = number_format($cost, 2);
        $priceFmt = number_format($price, 2);
        $discountFmt = number_format($discountAmt, 2);
        $productProfitFmt = number_format($productProfit, 2);
        $discountTypeEsc = htmlspecialchars($discountTypeP, ENT_QUOTES);

        $itemHtml .= <<<HTML
<div class="media" style="border-bottom:1px dashed #ddd; padding-bottom:6px; margin-bottom:6px;">
  <div class="media-left">
    <img src="$imgPath"
         style="width:110px; height:110px; border-radius:6px; border:0; object-fit:cover; background-color:#f8f8f8; box-shadow:0 1px 3px rgba(0,0,0,0.1);"
         onerror="this.onerror=null;this.src='<?= $defaultImg ?>';" />

  </div>
  <div class="media-body" style="padding-left:8px; line-height:1.3;">
    <small><b>$productName</b> ($sku)</small><br />
    <small>Qty: $qty</small><br />
    <small>Cost: RM $costFmt</small><br />
    <small>Price: RM $priceFmt</small><br />
    <small>Discount: $discountTypeEsc (RM $discountFmt)</small><br />
    <small><span class="text-success">Profit: RM $productProfitFmt</span></small>
  </div>
</div>
HTML;
    }

    // ✅ Calculate package profit (based on package selling price - total product cost)
    $packagePrice = floatval($row['price']);
    $packageProfit = $packagePrice - $totalCost;
    
    // ✅ Warning if package profit < total product profit
    $warningLabel = '';
    if ($packageProfit < $totalProfit) {
        $warningLabel = '<span class="badge badge-warning" style="margin-left:4px;">⚠️ Below Product Profit</span>';
    }

    $totalCostFmt = number_format($totalCost, 2);
    $packageProfitFmt = number_format($packageProfit, 2);
    $profitClass = ($packageProfit <= 0) ? 'text-danger' : 'text-success';

    // ✅ simplified summary: only total cost + total profit
    $itemHtml .= <<<HTML
<div style="border-top:1px solid #ccc; padding-top:6px; margin-top:6px; text-align:right;">
  <small><b>Total Product Cost:</b> RM $totalCostFmt</small><br />
  <small class="$profitClass"><b>Total Product Profit:</b> RM $totalProfit</small>
</div>
HTML;
?>
<tr>
    <td><?= $c++ ?></td>
    <td><?= htmlspecialchars($row['name']) ?></td>
    <td><span style="display:block; text-align:right;"><?= number_format($row['price'], 2) ?></span></td>
    <td><span style="display:block; text-align:center;"><?= intval($row['qty_set']) ?></span></td>
    <td><span style="display:block; text-align:right;"><?= number_format($row['direct_sponsor'], 2) ?></span></td>
    <td><span style="display:block; text-align:center;"><?= intval($row['commission_level']) ?></span></td>
    <td style="width:320px; vertical-align: top;"><?php echo $itemHtml; ?></td>
    <td class="<?= $profitClass ?>">
      <span style="display:block; text-align:right;">
        <?= $packageProfitFmt ?><br>
        <?= $packageProfit < $totalProfit ? '<center><i class="fa-3x fa-warning fa-solid fa-triangle-exclamation"></i> <br> <small> Package profit <br>is below of total product profit. </small></center>' : '' ?>
      </span>
    </td>
    <td>
        <i class="fa fa-edit action-icon text-primary" title="Edit"
           data-toggle="modal" data-target="#packageModal"
           onclick='openEditModal(<?= json_encode($row) ?>)'></i>
        <i class="fa fa-trash action-icon text-danger" title="Delete"
           data-toggle="modal" data-target="#deleteModal"
           onclick='openDeleteModal(<?= $row["id"] ?>)'></i>
    </td>
</tr>
<?php
} // end while
?>


                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</div>



<!-- Add/Edit Package Modal -->
<div class="modal fade" id="packageModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable" role="document">
    <div class="modal-content shadow-lg border-0 rounded-3">
      <form id="packageForm">
        <div class="modal-header text-white" style="background: linear-gradient(90deg, #1a2226, #222d32);">
          <h5 class="modal-title fw-bold" id="modalTitle" style="color: white;">Add Package</h5>
          <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>

        <div class="modal-body">
          <input type="hidden" name="id" id="packageId">
          <input type="hidden" name="action" value="save">

          <!-- Package Info -->
          <fieldset class="custom-fieldset">
            <legend class="custom-legend"><i class="fa fa-box me-1"></i> Package Information</legend>

            <div class="row g-3">
              <div class="col-md-6">
                <label class="fw-semibold">Package Name</label>
                <input type="text" name="name" id="name" class="form-control form-control-lg" placeholder="Enter package name" required>
              </div>
              <div class="col-md-6">
                <label class="fw-semibold">Package Price (RM)</label>
                <input type="number" step="0.01" name="price" id="price" class="form-control form-control-lg" placeholder="0.00" required>
              </div>
            </div>

            <div class="row g-3 pt-3">
              <div class="col-md-4">
                <label class="fw-semibold">Quantity Set</label>
                <input type="number" name="qty_set" id="qty_set" class="form-control form-control-lg" placeholder="e.g. 3" required>
              </div>
              <div class="col-md-4">
                <label class="fw-semibold">Direct Sponsor (RM)</label>
                <input type="number" step="0.01" name="direct_sponsor" id="direct_sponsor" class="form-control form-control-lg" placeholder="0.00" required>
              </div>
              <div class="col-md-4">
                <label class="fw-semibold">Commission Level</label>
                <input type="number" name="commission_level" id="commission_level" class="form-control form-control-lg" placeholder="e.g. 5" required>
              </div>
            </div>
          </fieldset>

          <!-- Package Items -->
          <fieldset class="custom-fieldset mt-4">
            <legend class="custom-legend"><i class="fa fa-cubes me-1"></i> Package Items</legend>

            <div class="table-responsive">
              <table class="table table-bordered align-middle" id="itemsTable">
                <thead class="table-light">
                  <tr>
                    <th style="width:45%">Product</th>
                    <th style="width:20%">Qty</th>
                    <th style="width:25%">Cost Price (RM)</th>
                    <th style="width:10%">
                      <button type="button" class="btn btn-success btn-sm" onclick="addItemRow()">
                        <i class="fa fa-plus"></i>
                      </button>
                    </th>
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </fieldset>
        </div>

        <div class="modal-footer">
          <button type="submit" class="btn btn-primary px-4">
            <i class="fa fa-save me-1"></i> Save
          </button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">
            <i class="fa fa-times me-1"></i> Cancel
          </button>
        </div>
      </form>
    </div>
  </div>
</div>


<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content shadow border-0 rounded-3">
      <form id="deleteForm">
        <div class="modal-header bg-danger text-white">
          <h5 class="modal-title fw-bold" style="color: white;"><i class="fa fa-exclamation-triangle me-2"></i> Confirm Delete</h5>
          <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body text-center">
          <p class="fs-5 mb-3">Are you sure you want to delete this package?</p>
          <input type="hidden" id="deleteId" name="id">
        </div>
        <div class="modal-footer justify-content-center">
          <button type="submit" class="btn btn-danger px-4">
            <i class="fa fa-trash me-1"></i> Delete
          </button>
          <button type="button" class="btn btn-secondary" data-dismiss="modal">
            <i class="fa fa-times me-1"></i> Cancel
          </button>
        </div>
      </form>
    </div>
  </div>
</div>


<script>
function addItemRow(item = null) {
    $.getJSON('package_action.php', { action: 'list' }, function(res) {
        if (!res.success) return alert('Failed to load products');

        let options = res.data.map(p => 
            `<option value="${p.id}" data-cost="${p.cost_price}">${p.product_name}</option>`
        ).join('');

        let newRow = $(`
            <tr class="item-row">
                <td>
                    <select name="product_id[]" class="form-control">
                        <option value="">-- Select Product --</option>
                        ${options}
                    </select>
                </td>
                <td><input type="number" name="qty[]" class="form-control" value="${item?.qty ?? 1}" min="1"></td>
                <td><input type="number" name="cost_price[]" class="form-control" value="${item?.cost_price ?? 0}" step="0.01" readonly></td>
                <td><button type="button" class="btn btn-danger btn-sm" onclick="$(this).closest('tr').remove()">x</button></td>
            </tr>
        `);

        $('#itemsTable tbody').append(newRow);

        // Set selected product if editing
        if (item) {
            let select = newRow.find('select');
            select.val(item.product_id);
            // Auto-fill cost from selected product
            let cost = select.find('option:selected').data('cost');
            newRow.find('input[name="cost_price[]"]').val(cost);
        }

        // When selecting product → auto update cost
        newRow.find('select').on('change', function() {
            let selectedCost = $(this).find('option:selected').data('cost') || 0;
            $(this).closest('tr').find('input[name="cost_price[]"]').val(selectedCost);
        });
    });
}


function openAddModal(){
    $('#modalTitle').text("Add Package");
    $('#packageForm')[0].reset();
    $('#packageId').val('');
    $('#itemsTable tbody').html('');
    addItemRow();
    $('#packageModal').modal('show');
}

function openEditModal(data){
    $('#modalTitle').text("Edit Package");
    $('#packageId').val(data.id);
    $('#name').val(data.name);
    $('#price').val(data.price);
    $('#qty_set').val(data.qty_set);
    $('#direct_sponsor').val(data.direct_sponsor);
    $('#commission_level').val(data.commission_level);
    $('#itemsTable tbody').html('');
    let items = [];
    try { items = JSON.parse(data.items); } catch(e){}
    items.forEach(it => addItemRow(it));
    $('#packageModal').modal('show');
}

function openDeleteModal(id){
    $('#deleteId').val(id);
    $('#deleteModal').modal('show');
}

$('#packageForm').on('submit', function(e){
    e.preventDefault();
    $.ajax({
        url: 'package_action.php',
        type: 'POST',
        data: $(this).serialize(),
        dataType: 'json',
        success: function(res){
            alert(res.message);
            if(res.success) location.reload();
        }
    });
});

$('#deleteForm').on('submit', function(e){
    e.preventDefault();
    $.post('package_action.php', {action:'delete', id:$('#deleteId').val()}, function(res){
        alert(res.message);
        if(res.success) location.reload();
    },'json');
});


</script>

<?php include "_footer2.php"; ?>
