<?php error_reporting(0); 

if($this->input->get('success') == '1'): ?>
<script>
    alert("Item Added Successfully");
</script>
<?php elseif($this->input->get('success') == '0'): ?>
<script>
    alert("Failed to save item. Try again.");
</script>
<?php endif; ?>
<?php 
$cookie = $_COOKIE['user_data'] ?? '';
            $json = urldecode($cookie);
            $data = json_decode($json, true);
            $privelegeId = $data['privelegeId'];

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Item</title>
    
    <!-- Load jQuery FIRST -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- Load Bootstrap CSS -->
    <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    
    Load Bootstrap JS (requires jQuery) - MUST be before jQuery UI -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    
    <!-- Load jQuery UI CSS -->
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
    
    <!-- Load jQuery UI (requires jQuery) -->
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
    
    <!-- Load InputMask (optional) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/5.0.8/jquery.inputmask.min.js"></script>

    <!-- jQuery UI (optional) -->
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

    <style>
.glyphicon {
    top: -2px !important;
}
      /* Add this to your existing CSS */
body.modal-open {
    overflow: auto !important;
    padding-right: 0 !important;
}

.modal-backdrop {
    z-index: 1040 !important;
}

.modal {
    z-index: 1050 !important;
}

/* Fix for blurred background after modal close */
body:not(.modal-open) {
    overflow: auto !important;
}
    /* Your existing styles... */
    .btn-fixed-size {
        width: 28px !important;
        height: 28px !important;
        min-width: 28px !important;
        min-height: 28px !important;
        padding: 0 !important;
        line-height: 26px !important;
        text-align: center !important;
    }

    .btn-fixed-size i.glyphicon {
        line-height: inherit !important;
        margin: 0 !important;
    }

    /* For input group buttons */
    .input-group-btn .btn-fixed-size {
        margin-left: -1px;
    }

    /* For table remove buttons */
    .btnRemoveTd.btn-fixed-size {
        font-size: 14px !important;
    }

    /* For base unit input group */
    #baseUnitGroup .input-group-btn .btn-fixed-size {
        margin-left: 0 !important;
    }

    /* Modal styles */
    .modal-header {
        background: linear-gradient(to right, #2c3e50, #4ca1af);
        color: white;
        padding: 10px 15px;
    }

    .modal-header .close {
        color: white;
        opacity: 0.8;
    }

    .modal-header .close:hover {
        opacity: 1;
    }

    .modal-title {
        font-weight: 600;
    }

    /* Existing styles */
    .compact-container{
        max-width:1200px;margin:0 auto;padding:15px;background:#fff;
        border-radius:5px;box-shadow:0 2px 10px rgba(0,0,0,0.1)
    }
    .compact-table{width:100%;border-collapse:collapse;margin-bottom:6px}
    .compact-table td{padding:4px;font-size:12px;vertical-align:middle;padding-right: 50px !important;}
    .compact-table td.label{
        font-weight:600;
        color:#000;              /* BLACK TEXT */
        background:#ffffff;     /* remove grey bg */
        width:12%;
        text-align: right !important;
    white-space: nowrap;
    padding-right: 0px !important;   /* controls distance to textbox */
    padding-left: 0 !important;
    }

    .form-control{height:28px!important;font-size:12px!important;padding:3px 6px!important}
    .units-container{display:flex;gap:10px;margin-top:6px}
    .unit-box{flex:1;border:1px solid #ddd;padding:8px;border-radius:4px}
    .unit-box h5{margin:0 0 6px;font-size:12px;font-weight:600}
    .submit-btn-container{text-align:center;margin-top:10px}

    .page-title-bar{
        background: linear-gradient(to right, #2c3e50, #4ca1af);
        color: #fff;padding:10px 15px;margin-bottom:12px;
        border-radius:4px;font-size:16px;font-weight:600;
    }
    
    /* Brand Modal specific styles */
    .brand-form-group {
        margin-bottom: 15px;
    }
    .brand-form-group label {
        font-weight: 600;
        margin-bottom: 5px;
        display: block;
        color: #333;
    }

/* New Style */
/* ZERO GAP between label and textbox */
.compact-table td.label {
    text-align: right !important;
    padding-right: 0 !important;   /* NO SPACE */
    padding-left: 0 !important;
    white-space: nowrap;
}

.compact-table td:not(.label) {
    padding-left: 0 !important;    /* NO SPACE */
}


    </style>
</head>
<body>

<!-- =============================== -->
<!-- ADD BRAND MODAL -->
<!-- =============================== -->
<div class="modal fade" id="addBrandModal" tabindex="-1" role="dialog" aria-labelledby="addBrandModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="addBrandModalLabel">
                    <i class="glyphicon glyphicon-tag"></i> Add Brand
                </h4>
            </div>
            <div class="modal-body">
                <div class="brand-form-group">
                    <label for="brandCode">Brand Code</label>
                    <input type="text" class="form-control" id="brandCode" 
                           placeholder="Enter brand code" required
                           autocomplete="off">
                </div>
                <div class="brand-form-group">
                    <label for="brandName">Brand Name</label>
                    <input type="text" class="form-control" id="brandName" 
                           placeholder="Enter brand name" required
                           autocomplete="off">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">
                    <i class="glyphicon glyphicon-remove"></i> Close
                </button>
                <button type="button" class="btn btn-primary" id="saveBrandBtn">
                    <i class="glyphicon glyphicon-ok"></i> Add Brand
                </button>
            </div>
        </div>
    </div>
</div>

<!-- =============================== -->
<!-- ADD UNIT MODAL -->
<!-- =============================== -->
<div class="modal fade" id="addUnitModal" tabindex="-1" role="dialog" aria-labelledby="addUnitModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="addUnitModalLabel">
                    <i class="glyphicon glyphicon-plus"></i> Add Unit
                </h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="newUnitName">Unit Name</label>
                    <input type="text" class="form-control" id="newUnitName" 
                           placeholder="Enter unit name" required
                           autocomplete="off">
                    <small class="text-muted">e.g., Kilogram, Liter, Meter, Piece</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">
                    <i class="glyphicon glyphicon-remove"></i> Close
                </button>
                <button type="button" class="btn btn-primary" id="saveNewUnit">
                    <i class="glyphicon glyphicon-ok"></i> Add
                </button>
            </div>
        </div>
    </div>
</div>
<!-- =============================== -->

<div class="compact-container">

<div class="page-title-bar">
<i class="glyphicon glyphicon-plus"></i> ADD NEW ITEM
</div>
<!-- ngk -->
 <!-- <form id="importFile"
      method="post"
      enctype="multipart/form-data"
      class="form-inline">

    <input type="file"
           class="form-control"
           name="file"
           id="importExcel"
           accept=".xlsx"
           required />

    <button type="button"
            onclick="importExcelData()"
            class="btn btn-warning btn-sm">
        Import
    </button>
</form> -->
<!-- ngk -->

<form action="<?= base_url('itemMaster/getdata'); ?>" method="POST" id="mainForm">

<table class="compact-table">
<colgroup>
  <col style="width:5%"><col style="width:28%">
  <col style="width:5%"><col style="width:28%">
  <col style="width:5%"><col style="width:29%">
</colgroup>



<tr>
<td class="label">Brand</td>
<td>
  <div class="input-group">
    <input type="text" id="brandId" name="brandId" class="form-control" placeholder="Brand" required>
    <span class="input-group-btn">
      <button type="button" class="btn btn-success btn-xs btn-fixed-size" data-toggle="modal" data-target="#addBrandModal">
        <i class="glyphicon glyphicon-plus"></i>
      </button>
    </span>
  </div>
  <input type="hidden" id="brandIdHidden" name="brandIdHidden">
</td>

<td class="label">Category</td>
<td><select id="categoryId" name="categoryId" class="form-control"></select></td>

<td class="label">Title</td>
<td><input type="text" name="tittle" class="form-control" required></td>
</tr>

<tr>
<td class="label">Part No</td>
<td><input type="text" name="partNo" class="form-control"></td>

<td class="label">Qty</td>
<td><input type="text" id="quantity" name="quantity" onkeyup="checkNumeric(this.id)" class="form-control"></td>

<td class="label">Location</td>
<td><input type="text" name="location" class="form-control"></td>
</tr>

<tr>
<td class="label">Min Retail</td>
<td><input type="text" id="minRetailPrice" name="minRetailPrice" onkeyup="checkNumeric(this.id)" class="form-control"></td>

<td class="label">Cost</td>
<td><input type="text" id="costPrice" name="costPrice" onkeyup="checkNumeric(this.id)" class="form-control"></td>

<td class="label">VAT %</td>
<td><input type="text" id="vatPer" name="vatPer" onkeyup="checkNumeric(this.id)" class="form-control"></td>
</tr>

<tr>
<td class="label">Description</td>
<td><input type="text" name="description" class="form-control"></td>

<td class="label">Barcode</td>
<td><input type="text" name="generateBarcode" class="form-control"></td>

<td class="label">Note</td>
<td><input type="text" name="note" class="form-control"></td>
</tr>

<?php if(isset($privilageId) && $privilageId==11): ?>
<tr>
<td class="label">Expiry</td>
<td><input type="text" name="expiryDate" class="form-control datepicker"></td>

<td class="label">Mfg</td>
<td><input type="text" name="manufacturingDate" class="form-control datepicker"></td>

<td class="label">Batch</td>
<td><input type="text" name="batchNo" class="form-control"></td>
</tr>
<?php endif; ?>

</table>

<div class="units-container">

<div class="unit-box">
<h5>Base Unit</h5>
<!-- Modified Base Unit with plus button -->
<div class="input-group" id="baseUnitGroup">
    <select id="baseUnit" name="baseUnit" class="form-control" required></select>
    <span class="input-group-btn">
        <button type="button" class="btn btn-success btn-xs btn-fixed-size" id="addBaseUnitBtn" title="Add New Unit">
            <i class="glyphicon glyphicon-plus"></i>
        </button>
    </span>
</div>
</div>

<div class="unit-box">
<h5>Other Units</h5>
<table width="100%" id="unitTable">
<thead>
<tr>
<td width="45%"><select id="unit" class="form-control"></select></td>
<td width="35%"><input id="multiple" class="form-control" placeholder="Multiple"></td>
<td width="20%"><button type="button" id="addUnit" class="btn btn-success btn-xs btn-fixed-size">+</button></td>
</tr>
</thead>
<tbody>
<!-- Dynamic rows will be added here -->
</tbody>
</table>
</div>

</div>

<div class="submit-btn-container">
<?php if($privelegeId==1||$privelegeId==4){ ?>
<button type="submit" class="btn btn-primary">
<i class="glyphicon glyphicon-save"></i> SAVE ITEM
</button>
<?php } ?>

</div>

</form>
</div>

<script>

  /*function submitForm(){
    alert ("Item Added...");
  }*/
// Use jQuery.noConflict if there are conflicts
jQuery(document).ready(function($) {
    'use strict';
    
    // Prevent form submission if it's an AJAX request
    $(document).on('submit', '#mainForm', function(e) {
        if ($(this).data('ajax-submit') === true) {
            e.preventDefault();
            return false;
        }
        return true;
    });
    
    // Unit Dynamic Row Add
    var i = 1;
    $('#addUnit').click(function() {
        i++;
        
        var unitId     = $('#unit').val();
        var unitName   = $("#unit :selected").text();
        var multiple   = $('#multiple').val();
        
        if(unitId=='' || multiple==''){
            alert("Please select a unit and enter a multiple value");
            return;
        } else { 
            var content = '<tr id="row' + i + '">' +
                '<td>' +
                    '<input type="hidden" class="form-control input-sm" name="unitId[]" value="' + unitId + '" readonly />' +
                    '<input type="text" class="form-control input-sm" value="' + unitName + '" readonly />' +
                '</td>' +
                '<td>' +
                    '<input type="text" class="form-control input-sm" name="multiple[]" value="' + multiple + '" readonly />' +
                '</td>' +
                '<td>' +
                    '<button type="button" class="btn btn-danger btnRemoveTd btn-xs btn-fixed-size" style="font-size: 16px;" data-row="'+i+'">' +
                        '<i class="glyphicon glyphicon-remove"></i>' +
                    '</button>' +
                '</td>' +
            '</tr>';

            $('#unitTable tbody').append(content);
            $("#unit").val("");
            $("#multiple").val("");
        }
    });

    // Remove dynamic row
    $(document).on('click', '.btnRemoveTd', function(){
        var rowId = $(this).data('row');
        $('#row'+rowId).remove();
    });

    // Add Base Unit Modal Trigger
    $('#addBaseUnitBtn').click(function(e){
        e.preventDefault();
        $('#addUnitModal').modal('show');
    });

    // Save new unit function - FIXED MODAL CLOSE
    function saveNewUnit() {
        var unitName = $('#newUnitName').val().trim();
        
        if(!unitName) {
            alert('Please enter unit name');
            $('#newUnitName').focus();
            return;
        }
        
        // Show loading state
        var $btn = $('#saveNewUnit');
        var originalText = $btn.html();
        $btn.prop('disabled', true).html('<i class="glyphicon glyphicon-refresh glyphicon-spin"></i> Adding...');
        
        // Mark as AJAX request
        $('#mainForm').data('ajax-submit', true);
        
        // AJAX call to add unit
        $.ajax({
            url: "<?= site_url('itemMaster/addUnitAjax'); ?>",
            type: "POST",
            dataType: "json",
            data: {
                unitName: unitName,
                <?php if($this->config->item('csrf_protection') === TRUE): ?>
                <?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>'
                <?php endif; ?>
            },
            success: function(response) {
                if(response.success) {
                    // Add new option to both select boxes
                    var newOption = '<option value="' + response.unitId + '">' + response.unitName + '</option>';
                    $('#baseUnit').append(newOption);
                    $('#unit').append(newOption);
                    
                    // Select the newly added unit in base unit
                    $('#baseUnit').val(response.unitId);
                    
                    // Clear the unit selection and multiple field in Other Units section
                    $('#unit').val('');
                    $('#multiple').val('');
                    
                    // Clear input
                    $('#newUnitName').val('');
                    
                    // Show success message
                    alert('Unit "' + response.unitName + '" added successfully!');
                    
                    // FIXED: Properly close modal and remove backdrop
                    $('#addUnitModal').modal('hide');
                    $('body').removeClass('modal-open');
                    $('.modal-backdrop').remove();
                    
                } else {
                    alert('Error: ' + response.message);
                    $btn.prop('disabled', false).html(originalText);
                }
                $('#mainForm').data('ajax-submit', false);
            },
            error: function(xhr, status, error) {
                alert('Server error occurred. Please try again.');
                $btn.prop('disabled', false).html(originalText);
                $('#mainForm').data('ajax-submit', false);
            }
        });
    }

    // Bind save button click for unit
    $('#saveNewUnit').click(saveNewUnit);
    
    // Save Brand function - FIXED MODAL CLOSE
    function saveBrand() {
        var brandCode = $('#brandCode').val().trim();
        var brandName = $('#brandName').val().trim();
        
        if(!brandCode) {
            alert('Please enter brand code');
            $('#brandCode').focus();
            return;
        }
        
        if(!brandName) {
            alert('Please enter brand name');
            $('#brandName').focus();
            return;
        }
        
        // Show loading state
        var $btn = $('#saveBrandBtn');
        var originalText = $btn.html();
        $btn.prop('disabled', true).html('<i class="glyphicon glyphicon-refresh glyphicon-spin"></i> Adding...');
        
        // Mark as AJAX request
        $('#mainForm').data('ajax-submit', true);
        
        // AJAX call to add brand
        $.ajax({
            url: "<?= site_url('itemMaster/addBrandAjax'); ?>",
            type: "POST",
            dataType: "json",
            data: {
                brandCode: brandCode,
                brandName: brandName,
                <?php if($this->config->item('csrf_protection') === TRUE): ?>
                <?php echo $this->security->get_csrf_token_name(); ?>: '<?php echo $this->security->get_csrf_hash(); ?>'
                <?php endif; ?>
            },
            success: function(response) {
                if(response.success) {
                    // Update the brand autocomplete field
                    $('#brandId').val(brandName);
                    $('#brandIdHidden').val(response.brandId);
                    
                    // Clear inputs
                    $('#brandCode').val('');
                    $('#brandName').val('');
                    
                    // Show success message
                    alert('Brand "' + brandName + '" added successfully!');
                    
                    // FIXED: Properly close modal and remove backdrop
                    $('#addBrandModal').modal('hide');
                    $('body').removeClass('modal-open');
                    $('.modal-backdrop').remove();
                    
                } else {
                    alert('Error: ' + response.message);
                    $btn.prop('disabled', false).html(originalText);
                }
                $('#mainForm').data('ajax-submit', false);
            },
            error: function(xhr, status, error) {
                alert('Server error occurred. Please try again.');
                $btn.prop('disabled', false).html(originalText);
                $('#mainForm').data('ajax-submit', false);
            }
        });
    }

    // Bind save button click for brand
    $('#saveBrandBtn').click(saveBrand);
    
    // Enter key support for brand modal
    $('#brandCode, #brandName').keypress(function(e){
        if(e.which == 13) {
            saveBrand();
            return false;
        }
    });
    
    // Clear brand form when modal closes
    $('#addBrandModal').on('hidden.bs.modal', function () {
        $('#brandCode').val('');
        $('#brandName').val('');
        $('#saveBrandBtn').prop('disabled', false).html('<i class="glyphicon glyphicon-ok"></i> Add Brand');
    });
    
    // Focus on first input when brand modal shown
    $('#addBrandModal').on('shown.bs.modal', function () {
        $('#brandCode').focus();
    });
    
    // Clear unit form when modal closes
    $('#addUnitModal').on('hidden.bs.modal', function () {
        $('#newUnitName').val('');
        $('#saveNewUnit').prop('disabled', false).html('<i class="glyphicon glyphicon-ok"></i> Add');
    });

    // Enter key support for unit modal
    $('#newUnitName').keypress(function(e){
        if(e.which == 13) {
            saveNewUnit();
            return false;
        }
    });

    // Focus on input when unit modal shown
    $('#addUnitModal').on('shown.bs.modal', function () {
        $('#newUnitName').focus();
    });

    /* Base Unit */
    function loadUnits(){
        $.getJSON("<?= site_url('itemMaster/get_baseunit_ajax'); ?>", function(res){
            let html = '<option value="">Select</option>';
            if(res.data) {
                $.each(res.data, function(i, r){
                    html += '<option value="'+r.unitId+'">'+r.unitName+'</option>';
                });
            }
            $('#baseUnit,#unit').html(html);
        });
    }
    
    loadUnits();

    /* Category */
    $.getJSON("<?= site_url('itemMaster/get_category_ajax'); ?>", function(res){
        let html = '<option value="">Select</option>';
        if(res.data) {
            $.each(res.data, function(i, r){
                html += '<option value="'+r.categoryId+'">'+r.categoryName+'</option>';
            });
        }
        $('#categoryId').html(html);
    });

    /* Brand Autocomplete */
    $("#brandId").autocomplete({
        minLength: 1,
        source: function(req, res){
            $.post("<?= site_url('itemMaster/getBrandAutoComplete'); ?>",
                {search: req.term}, res, 'json');
        },
        select: function(e, ui){
            $("#brandId").val(ui.item.label);
            $("#brandIdHidden").val(ui.item.value);
            return false;
        }
    });

    /* Datepicker */
    $(".datepicker").datepicker({dateFormat:'yy-mm-dd'});
});

// Global function for checkNumeric (needed for inline onkeyup)
function checkNumeric(id){
    let v = document.getElementById(id).value;
    if(isNaN(v)) document.getElementById(id).value = v.replace(/\D+/g,'');
}

// Global function for checkNumeric (needed for inline onkeyup)
function checkNumeric(id){
    let v = document.getElementById(id).value;
    if(isNaN(v)) document.getElementById(id).value = v.replace(/\D+/g,'');
}
</script>

</body>

<!-- ngk -->
 <script>
 function importExcelData() {

    var file_data = $("#importExcel").prop("files")[0];

    if (!file_data) {
        alert("Please select an Excel file");
        return;
    }

    var form_data = new FormData();
    form_data.append("file", file_data); // MUST match PHP

    $.ajax({
        url: "<?= site_url('itemMaster/importExcelIndb'); ?>",
        type: "POST",
        data: form_data,
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {

            console.log(data); // DEBUG

            if (data.trim() == "1") {
                swal({
                    text: "Successfully imported !!",
                    icon: "success",
                    timer: 2000,
                    buttons: false
                });
            } else {
                swal({
                    text: data,
                    icon: "error"
                });
            }
        },
        error: function (xhr) {
            console.log(xhr.responseText);
            alert("Upload failed");
        }
    });
}
</script>
 <!-- ngk -->

</html>