<?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";
include "_functions.php";
require "conn.php";
?>
<style>
.action-icon { cursor:pointer; margin-right:10px; }
.img-preview { width:60px; height:60px; object-fit:cover; border-radius:5px; }
.table-responsive { overflow-x:auto; }
</style>
<div id="page-wrapper">
<div id="page-inner">
    <div class="row">
        <div class="col-md-12">
            <h2>Product 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 d-inline-block">
                <label for="invoice_no">Product Name :</label>
                <input type="text" id="invoice_no" name="invoice_no" 
                    value="<?= htmlspecialchars($_GET['invoice_no'] ?? '') ?>" 
                    placeholder="Search Product..." 
                    class="form-control" style="max-width:200px;">
            </div>
            <div class="form-group mb-2 d-inline-block">
                <button type="submit" class="btn btn-primary">Search</button>
                <button type="button" class="btn btn-success" data-toggle="modal" data-target="#productModal" onclick="openAddModal()">+ Add Product</button>
            </div>
        </div>
    </form>

    <div class="panel panel-default">
        <div class="panel-heading">List of All Products</div>
        <div class="panel-body">
            <div class="table-responsive">
                <table class="table table-striped table-bordered table-hover">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Image</th>
                            <th>Name</th>
                            <th>SKU</th>
                            <th>Price</th>
                            <th>Cost</th>
                            <th>Discount Type</th>
                            <th>Discount Value</th>
                            <th>Description</th>
                            <th>Created</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
<?php
$c=1;
$keyword = mysqli_real_escape_string($con, $_GET['invoice_no'] ?? '');
$q = $keyword ? "WHERE product_name LIKE '%$keyword%'" : '';
$res = mysqli_query($con,"SELECT * FROM products $q ORDER BY created_at DESC");
while($row=mysqli_fetch_assoc($res)){ 
    $finalPrice = $row['price'];
    if($row['discount_type']==='PERCENT') $finalPrice -= $finalPrice*($row['discount_value']/100);
    elseif($row['discount_type']==='FIXED') $finalPrice -= $row['discount_value'];
    $finalPrice = max(0,$finalPrice);
    $isLoss = $finalPrice < $row['cost_price'];
?>
<tr id="row-<?= $row['id'] ?>" <?= $isLoss?'style="background-color:#ffe5e5"':'' ?>>
    <td><?= $c++ ?></td>
    <td>
        <?php if($row['img']): ?>
            <img src="uploads/products/<?= htmlspecialchars($row['img']) ?>" class="img-preview">
        <?php else: ?>
            <img src="uploads/products/no_img.png" class="img-preview">
        <?php endif; ?>
    </td>
    <td><?= htmlspecialchars($row['product_name']) ?></td>
    <td><?= htmlspecialchars($row['sku']) ?></td>
    <td><?= number_format($row['price'],2) ?></td>
    <td><?= number_format($row['cost_price'],2) ?></td>
    <td><?= htmlspecialchars($row['discount_type']) ?></td>
    <td><?= number_format($row['discount_value'],2) ?></td>
    <td><?= htmlspecialchars($row['description']) ?></td>
    <td><?= date("d/m/Y H:i", strtotime($row['created_at'])) ?></td>
    <td>
        <i class="fa fa-edit action-icon text-primary" title="Edit"
           data-toggle="modal" data-target="#productModal"
           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 } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</div>

<!-- Add/Edit Product Modal -->
<div class="modal fade" id="productModal" 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="productForm" enctype="multipart/form-data">
        <div class="modal-header text-white" style="background: linear-gradient(90deg, #1a2226, #222d32);">
          <h5 class="modal-title fw-bold" id="modalTitle">Add Product</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="productId">
          <input type="hidden" name="action" value="save">
            
          <!-- Image Upload Section -->
          <fieldset class="custom-fieldset">
            <legend class="custom-legend"><i class="fa fa-image me-1"></i> Product Image</legend>

            <div class="mb-3 text-center">
              <div id="previewContainer">
                <img id="imgPreview" 
                     src="img/company_logo_blur.png" 
                     class="img-thumbnail shadow-sm"
                     style="border:0px; max-height:200px; border-radius:10px;" 
                     alt="Product Image Preview"
                     onerror="this.onerror=null; this.src='img/company_logo_blur.png';">
              </div>
            </div>

            <div class="mb-3">
              <input type="file" name="img" id="img" accept="image/*" capture="environment" class="form-control form-control-lg" onchange="previewImage(event)">
              <small class="form-text text-muted">Accepted formats: jpg, jpeg, png, heic</small>
            </div>
          </fieldset>    
            
          <!-- Product Details -->
          <fieldset class="custom-fieldset">
            <legend class="custom-legend"><i class="fa fa-box me-1"></i> Product Details</legend>

            <div class="row g-3">
              <div class="col-md-6">
                <label class="fw-semibold">Product Name</label>
                <input type="text" id="productName" name="product_name" class="form-control form-control-lg" placeholder="Enter product name" required>
              </div>
              <div class="col-md-6">
                <label class="fw-semibold">SKU</label>
                <input type="text" id="sku" name="sku" class="form-control form-control-lg" placeholder="SKU or barcode">
              </div>
            </div>
          </fieldset>

          <!-- Pricing Section -->
          <fieldset class="custom-fieldset">
            <legend class="custom-legend"><i class="fa fa-tags me-1"></i> Pricing & Discount</legend>
            <div class="row g-3">
              <div class="col-md-6">
                <label class="fw-semibold">Price (RM)</label>
                <input type="number" step="0.01" id="price" name="price" class="form-control form-control-lg" placeholder="0.00" required>
              </div>
              <div class="col-md-6">
                <label class="fw-semibold">Cost Price</label>
                <input type="number" step="0.01" id="costPrice" name="cost_price" class="form-control form-control-lg" placeholder="0.00">
              </div>
              <div class="col-md-6">
                <label class="fw-semibold">Discount Type</label>
                <select id="discountType" name="discount_type" class="form-control form-control-lg">
                  <option value="NONE">NONE</option>
                  <option value="PERCENT">PERCENT</option>
                  <option value="FIXED">FIXED</option>
                </select>
              </div>              
              <div class="col-md-6">
                <label class="fw-semibold">Discount Value</label>
                <input type="number" step="0.01" id="discountValue" name="discount_value" class="form-control form-control-lg" placeholder="0.00">
              </div>
            </div>

            <div class="row g-3 pt-3">

              <div class="col-md-12">
                <label class="fw-semibold">Description</label>
                <textarea id="description" name="description" class="form-control form-control-lg" rows="3" placeholder="Short product description..."></textarea>
              </div>
            </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 Product 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 border-0 shadow-sm rounded-3">
      <form id="deleteForm">
        <div class="modal-header text-white" style="background: linear-gradient(90deg, #a94442, #8b0000);">
          <h5 class="modal-title fw-bold"><i class="fa fa-exclamation-triangle me-1"></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 py-4">
          <p class="fs-5 mb-3 text-secondary">Are you sure you want to delete this product?</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">Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
function previewImage(event){
    const reader = new FileReader();
    reader.onload = () => document.getElementById('imgPreview').src = reader.result;
    reader.readAsDataURL(event.target.files[0]);
}

function openAddModal(){
    $('#modalTitle').text("Add Product");
    $('#productForm')[0].reset();
    $('#productId').val('');
    $('#imgPreview').attr('src','img/company_logo_blur.png');
    $('#productModal').modal('show');
}

function openEditModal(data){
    $('#modalTitle').text("Edit Product");
    $('#productId').val(data.id);
    $('#productName').val(data.product_name);
    $('#sku').val(data.sku);
    $('#price').val(data.price);
    $('#costPrice').val(data.cost_price);
    $('#discountType').val(data.discount_type);
    $('#discountValue').val(data.discount_value);
    $('#description').val(data.description);
    $('#imgPreview').attr('src', data.img ? 'uploads/products/' + data.img : 'img/company_logo_blur.png');
    $('#productModal').modal('show');
}

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

$('#productForm').on('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);

    $.ajax({
        url: 'product_action.php',
        type: 'POST',
        data: formData,
        processData: false,  // prevent jQuery from processing data
        contentType: false,  // prevent jQuery from setting contentType
        dataType: 'json',
        beforeSend: function() {
            console.log('⏳ Sending request...');
        },
        success: function(data) {
            console.log('✅ Response received:', data);

            // Show backend message
            alert(data.message);

            // Reload only on success
            if (data.success) location.reload();
        },
        error: function(xhr, status, error) {
            console.error('❌ AJAX Error:', status, error);
            console.log(xhr.responseText);
            alert('An error occurred: ' + error);
        }
    });
});


$('#deleteForm').on('submit', function(e){
    e.preventDefault();
    const id = $('#deleteId').val();
    $.post('product_action.php', {action:'delete', id:id}, function(data){
        alert(data.message);
        if(data.success) location.reload();
    }, 'json');
});
</script>

<style>
.custom-fieldset {
  border: 1px solid #ccc;
  padding: 15px 20px;
  margin-bottom: 15px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.08);
  background: #fdfdfd;
}
.custom-legend {
  font-size: 13px;
  font-weight: 600;
  color: #555;
  width: auto;
  padding: 0 10px;
  border: none;
}
.modal-content {
  border-radius: 12px;
}
</style>



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