<?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>
    .badge-custom {
        padding: 8px 12px;
        font-size: 0.9em;
    }
</style>

<div id="page-wrapper">
    <div id="page-inner">
        <div class="row">
            <div class="col-md-12">
                <h2>Order List</h2><button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#productModal" onclick="openAddModal()">+ Add Product</button>
            </div>
        </div>
        <hr />

        <div class="row">
            <div class="col-md-12">
                <!-- Advanced Tables -->
                <div class="panel panel-default">
                    <div class="panel-heading">All Products</div>
                    <div class="panel-body">
                        <div class="table-responsive">
                            <table class="table table-striped table-bordered table-hover" id="productTable">
                                <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;
$res = mysqli_query($con,"SELECT * FROM products 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/<?= htmlspecialchars($row['img']) ?>" class="img-preview" id="img_preview_<?= $row['id'] ?>">
        <?php else: ?>
            <span class="text-muted">No Image</span>
        <?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-bs-toggle="modal" data-bs-target="#productModal"
           onclick='openEditModal(<?= json_encode($row) ?>)'></i>
        <i class="fa fa-trash action-icon text-danger" title="Delete" data-bs-toggle="modal" data-bs-target="#deleteModal"
           onclick='openDeleteModal(<?= $row["id"] ?>)'></i>
    </td>
</tr>
<?php } ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div class="modal fade" id="productModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
          <form id="productForm" enctype="multipart/form-data">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Add Product</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="id" id="productId">
                <input type="hidden" name="action" value="save">
                <div class="row mb-2">
                    <div class="col-md-6"><label>Product Name</label><input type="text" id="productName" name="product_name" class="form-control" required></div>
                    <div class="col-md-6"><label>SKU</label><input type="text" id="sku" name="sku" class="form-control"></div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-4"><label>Price</label><input type="number" step="0.01" id="price" name="price" class="form-control" required></div>
                    <div class="col-md-4"><label>Cost Price</label><input type="number" step="0.01" id="costPrice" name="cost_price" class="form-control"></div>
                    <div class="col-md-4">
                        <label>Discount Type</label>
                        <select id="discountType" name="discount_type" class="form-control">
                            <option value="NONE">NONE</option>
                            <option value="PERCENT">PERCENT</option>
                            <option value="FIXED">FIXED</option>
                        </select>
                    </div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-4"><label>Discount Value</label><input type="number" step="0.01" id="discountValue" name="discount_value" class="form-control"></div>
                    <div class="col-md-8"><label>Description</label><textarea id="description" name="description" class="form-control"></textarea></div>
                </div>
                <div class="row mb-2">
                    <div class="col-md-6">
                        <label>Image</label>
                        <input type="file" class="form-control" name="img" id="img" onchange="previewImage(event)">
                        <img id="imgPreview" class="img-preview mt-2"/>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-primary">Save</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- Delete Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <form id="deleteForm">
            <div class="modal-header">
                <h5 class="modal-title">Confirm Delete</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this product?</p>
                <input type="hidden" id="deleteId" name="id">
            </div>
            <div class="modal-footer">
                <button class="btn btn-danger">Delete</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            </div>
          </form>
        </div>
      </div>
    </div>

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Image preview
function previewImage(event){
    var reader = new FileReader();
    reader.onload = function(){
        document.getElementById('imgPreview').src = reader.result;
    }
    reader.readAsDataURL(event.target.files[0]);
}

// Open Add Modal
function openAddModal(){
    document.getElementById('modalTitle').innerText = "Add Product";
    document.getElementById('productForm').reset();
    document.getElementById('productId').value = '';
    document.getElementById('imgPreview').src = '';
}

// Open Edit Modal
function openEditModal(data){
    document.getElementById('modalTitle').innerText = "Edit Product";
    document.getElementById('productId').value = data.id;
    document.getElementById('productName').value = data.product_name;
    document.getElementById('sku').value = data.sku;
    document.getElementById('price').value = data.price;
    document.getElementById('costPrice').value = data.cost_price;
    document.getElementById('discountType').value = data.discount_type;
    document.getElementById('discountValue').value = data.discount_value;
    document.getElementById('description').value = data.description;
    document.getElementById('imgPreview').src = data.img ? 'uploads/' + data.img : '';
}

// Open Delete Modal
function openDeleteModal(id){
    document.getElementById('deleteId').value = id;
}

// Handle Add/Edit submit
document.getElementById('productForm').addEventListener('submit', function(e){
    e.preventDefault();
    var formData = new FormData(this);
    fetch('product_action.php',{
        method:'POST',
        body: formData
    }).then(res=>res.json())
      .then(data=>{
        alert(data.message);
        if(data.success) location.reload();
    });
});

// Handle Delete submit
document.getElementById('deleteForm').addEventListener('submit', function(e){
    e.preventDefault();
    var id = document.getElementById('deleteId').value;
    fetch('product_action.php',{
        method:'POST',
        headers:{'Content-Type':'application/x-www-form-urlencoded'},
        body:'action=delete&id='+id
    }).then(res=>res.json())
      .then(data=>{
        alert(data.message);
        if(data.success) location.reload();
    });
});
</script>
