<?php
/* ImportLineItemsOPO.php - Enhanced with Modern Upload UI */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;
ob_start();
include('includes/session.inc');
$Title=_('Import OPO Line Items');
include('includes/newheader.php');
include('includes/SQL_CommonFunctions.inc');

$timenow = date('Y-m-d H:i:s');
$userid = $_SESSION['UserID'];

if (isset($_GET['id'])) {
    $_SESSION['id'] = stripslashes($_GET['id']);
}
$opno = $_SESSION['id'];

/* ── Process CSV Upload ── */
$uploadMessage = '';
$uploadSuccess = false;
$rowCount = 0;

if (isset($_FILES['userfile']) AND $_FILES['userfile']['name']) {
    $FieldTarget = 18;
    $InputError = 0;
    $FileName = $_FILES['userfile']['name'];
    $TempName = $_FILES['userfile']['tmp_name'];
    $FileSize = $_FILES['userfile']['size'];
    $FileHandle = fopen($TempName, 'r');
    $headRow = fgetcsv($FileHandle, 10000, ",");

    DB_Txn_Begin();

    $row = 1;
    while (($myrow = fgetcsv($FileHandle, 10000, ",")) !== FALSE) {
        $StockID = mb_strtoupper($myrow[0]);
        foreach ($myrow as &$value) {
            $value = trim($value);
        }

        $qty = $myrow[3];
        $price = $myrow[4];
        $totalprice = $qty * $price;
        $glcode = $myrow[5];
        $erpstockid = $myrow[0];
        $suppstockid = $myrow[1];
        $desc = $myrow[2];
        $shipmode = isset($myrow[7]) ? $myrow[7] : '';

        $sql = "INSERT INTO overseas_purchase_orders_details(
            id,erp_stockid,supplier_stockid,description,qty,unit_price,total_price,gl_code,department,shipment_mode,entered_by,entered_date
        ) VALUES (
            '" . DB_escape_string($opno) . "',
            '" . DB_escape_string($erpstockid) . "',
            '" . DB_escape_string($suppstockid) . "',
            '" . DB_escape_string($desc) . "',
            '" . DB_escape_string($qty) . "',
            '" . DB_escape_string($price) . "',
            '" . DB_escape_string($totalprice) . "',
            '" . DB_escape_string($glcode) . "',
            '" . DB_escape_string(isset($myrow[6]) ? $myrow[6] : '') . "',
            '" . DB_escape_string($shipmode) . "',
            '" . DB_escape_string($userid) . "',
            '" . DB_escape_string($timenow) . "'
        )";

        $ErrMsg = _('The item could not be added because');
        $DbgMsg = _('The SQL that was used to add the item failed was');
        $result = DB_query($sql, $ErrMsg, $DbgMsg);
        $row++;
    }

    DB_Txn_Commit();
    fclose($FileHandle);
    $rowCount = $row - 1;
    $uploadSuccess = true;
    $uploadMessage = 'Successfully imported ' . $rowCount . ' line items into OPO #' . $opno;
}
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"/>
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
:root{--opo-primary:#2AABB3;--opo-dark:#1E8F96;--opo-darker:#187278;--opo-light:#E6F7F8;--opo-text:#1F2937;--opo-muted:#6B7280;--opo-border:#E5E7EB;--opo-success:#52C41A;--opo-danger:#FF4D4F;--opo-radius:10px}

.imp-banner{background:linear-gradient(135deg,#187278 0%,#1E8F96 40%,#2AABB3 100%);border-radius:var(--opo-radius);padding:24px 32px 20px;margin:0 0 24px;position:relative;overflow:hidden;font-family:'Poppins',sans-serif}
.imp-banner::before{content:'';position:absolute;top:-50px;right:-30px;width:160px;height:160px;background:rgba(255,255,255,.06);border-radius:50%}
.imp-banner .breadcrumb{display:flex;gap:8px;font-size:12px;color:rgba(255,255,255,.7);margin-bottom:8px}
.imp-banner .breadcrumb a{color:rgba(255,255,255,.7);text-decoration:none}
.imp-banner .breadcrumb a:hover{color:#fff}
.imp-banner h1{color:#fff;font-size:20px;font-weight:700;margin:0;font-family:'Poppins',sans-serif}
.imp-banner h1 i{margin-right:10px;opacity:.9}

.imp-container{max-width:700px;margin:0 auto;padding:0 16px;font-family:'Poppins',sans-serif}

.imp-card{background:#fff;border-radius:var(--opo-radius);border:1px solid var(--opo-border);box-shadow:0 1px 3px rgba(0,0,0,.06);padding:28px 32px;margin-bottom:24px}
.imp-card h2{font-size:15px;font-weight:600;color:var(--opo-text);margin:0 0 6px;display:flex;align-items:center;gap:10px}
.imp-card h2 i{color:var(--opo-primary);font-size:18px}
.imp-card .subtitle{font-size:12px;color:var(--opo-muted);margin-bottom:20px}

.imp-opo-badge{display:inline-flex;align-items:center;gap:6px;background:var(--opo-light);color:var(--opo-dark);padding:6px 16px;border-radius:8px;font-size:14px;font-weight:700;margin-bottom:16px}

.imp-dropzone{border:2px dashed var(--opo-border);border-radius:12px;padding:48px 24px;text-align:center;transition:all .25s;cursor:pointer;background:#FAFBFC}
.imp-dropzone:hover,.imp-dropzone.dragover{border-color:var(--opo-primary);background:var(--opo-light)}
.imp-dropzone i.upload-icon{font-size:40px;color:#D1D5DB;margin-bottom:12px;display:block;transition:color .25s}
.imp-dropzone:hover i.upload-icon{color:var(--opo-primary)}
.imp-dropzone .main-text{font-size:14px;font-weight:600;color:var(--opo-text);margin-bottom:4px}
.imp-dropzone .sub-text{font-size:12px;color:var(--opo-muted)}
.imp-dropzone .browse-btn{display:inline-block;margin-top:14px;padding:8px 20px;background:var(--opo-primary);color:#fff;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;transition:background .2s}
.imp-dropzone .browse-btn:hover{background:var(--opo-darker)}

.imp-file-info{display:flex;align-items:center;gap:12px;padding:14px 16px;background:#F9FAFB;border-radius:8px;border:1px solid var(--opo-border);margin-top:16px}
.imp-file-info .file-icon{width:40px;height:40px;background:var(--opo-light);border-radius:8px;display:flex;align-items:center;justify-content:center;color:var(--opo-dark);font-size:18px}
.imp-file-info .file-details{flex:1}
.imp-file-info .file-name{font-size:13px;font-weight:600;color:var(--opo-text)}
.imp-file-info .file-size{font-size:11px;color:var(--opo-muted)}
.imp-file-info .remove-btn{color:var(--opo-danger);cursor:pointer;font-size:14px;padding:4px}

.imp-actions{display:flex;gap:12px;margin-top:20px}
.imp-btn{padding:10px 24px;border-radius:8px;font-family:'Poppins',sans-serif;font-size:13px;font-weight:600;border:none;cursor:pointer;transition:all .2s;display:inline-flex;align-items:center;gap:8px}
.imp-btn-primary{background:var(--opo-primary);color:#fff}
.imp-btn-primary:hover{background:var(--opo-darker)}
.imp-btn-outline{background:#fff;color:var(--opo-muted);border:1px solid var(--opo-border)}
.imp-btn-outline:hover{border-color:var(--opo-primary);color:var(--opo-dark)}
.imp-btn:disabled{opacity:.5;cursor:not-allowed}

.imp-format{background:#F9FAFB;border-radius:8px;padding:16px 20px;border:1px solid var(--opo-border);margin-top:20px}
.imp-format h4{font-size:12px;font-weight:600;color:var(--opo-text);margin:0 0 8px;display:flex;align-items:center;gap:6px}
.imp-format h4 i{color:var(--opo-primary)}
.imp-format-table{width:100%;font-size:11px;border-collapse:collapse}
.imp-format-table th{background:linear-gradient(135deg,#1E8F96,#2AABB3);color:#fff;padding:6px 10px;text-align:left;font-weight:500;white-space:nowrap}
.imp-format-table th:first-child{border-radius:6px 0 0 0}
.imp-format-table th:last-child{border-radius:0 6px 0 0}
.imp-format-table td{padding:6px 10px;border-bottom:1px solid var(--opo-border);color:var(--opo-muted)}

.imp-alert{padding:14px 18px;border-radius:8px;font-size:13px;font-weight:500;display:flex;align-items:center;gap:10px;margin-bottom:20px}
.imp-alert-success{background:#F6FFED;color:#389E0D;border:1px solid #B7EB8F}
.imp-alert-error{background:#FFF2F0;color:#CF1322;border:1px solid #FFA39E}
</style>

<div style="padding:0 8px;font-family:'Poppins',sans-serif">

<!-- ── Banner ── -->
<div class="imp-banner">
  <div class="breadcrumb">
    <a href="index.php"><i class="fa fa-home"></i> Home</a> <span>›</span>
    <a href="OverseasPurchaseOrders.php">Overseas Purchase Orders</a> <span>›</span>
    <span style="color:#fff">Import Line Items</span>
  </div>
  <h1><i class="fa fa-file-csv"></i> Import Line Items from CSV</h1>
</div>

<div class="imp-container">

<?php if($uploadSuccess){ ?>
  <div class="imp-alert imp-alert-success">
    <i class="fa fa-check-circle" style="font-size:18px"></i>
    <div>
      <strong>Import Successful!</strong><br>
      <span style="font-size:12px"><?php echo $uploadMessage; ?></span>
    </div>
  </div>
  <div style="text-align:center;margin-bottom:24px">
    <a href="OverseasPurchaseOrders.php" class="imp-btn imp-btn-primary"><i class="fa fa-arrow-left"></i> Back to Purchase Orders</a>
  </div>
<?php } else { ?>

<div class="imp-card">
  <div class="imp-opo-badge"><i class="fa fa-ship"></i> OPO #<?php echo $opno; ?></div>
  <h2><i class="fa fa-upload"></i> Upload CSV File</h2>
  <p class="subtitle">Import line items for Overseas Purchase Order #<?php echo $opno; ?>. Upload a CSV file following the format below.</p>

  <form id="importForm" action="ImportLineItemsOPO.php" method="post" enctype="multipart/form-data">
    <input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />
    <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />

    <div class="imp-dropzone" id="dropzone" onclick="document.getElementById('fileInput').click()">
      <i class="fa fa-cloud-arrow-up upload-icon"></i>
      <div class="main-text">Drag & drop your CSV file here</div>
      <div class="sub-text">or click to browse files (max 1 MB)</div>
      <div class="browse-btn">Browse Files</div>
    </div>
    <input type="file" name="userfile" id="fileInput" accept=".csv" style="display:none"/>

    <div id="fileInfoArea" style="display:none">
      <div class="imp-file-info">
        <div class="file-icon"><i class="fa fa-file-csv"></i></div>
        <div class="file-details">
          <div class="file-name" id="fileName">-</div>
          <div class="file-size" id="fileSize">-</div>
        </div>
        <div class="remove-btn" onclick="clearFile()"><i class="fa fa-times-circle"></i></div>
      </div>
    </div>

    <div class="imp-actions">
      <button type="submit" class="imp-btn imp-btn-primary" id="submitBtn" disabled>
        <i class="fa fa-upload"></i> Import Line Items
      </button>
      <a href="OverseasPurchaseOrders.php" class="imp-btn imp-btn-outline">
        <i class="fa fa-arrow-left"></i> Cancel
      </a>
    </div>
  </form>

  <!-- CSV Format Reference -->
  <div class="imp-format">
    <h4><i class="fa fa-info-circle"></i> Expected CSV Format (8 columns)</h4>
    <table class="imp-format-table">
      <thead>
        <tr><th>Col</th><th>Field</th><th>Example</th></tr>
      </thead>
      <tbody>
        <tr><td>A</td><td>ERP Stock ID</td><td>ITEM001</td></tr>
        <tr><td>B</td><td>Supplier Stock ID</td><td>SUP-A1</td></tr>
        <tr><td>C</td><td>Description</td><td>Fire Extinguisher 4.5kg</td></tr>
        <tr><td>D</td><td>Quantity</td><td>10</td></tr>
        <tr><td>E</td><td>Unit Price</td><td>125.50</td></tr>
        <tr><td>F</td><td>GL Code</td><td>5100</td></tr>
        <tr><td>G</td><td>Department</td><td>7</td></tr>
        <tr><td>H</td><td>Shipment Mode</td><td>Air Freight</td></tr>
      </tbody>
    </table>
    <p style="font-size:11px;color:var(--opo-muted);margin:10px 0 0"><i class="fa fa-lightbulb" style="color:var(--opo-primary)"></i> First row should be headers (they will be skipped). Total price is auto-calculated as Qty × Unit Price.</p>
  </div>
</div>

<?php } ?>

</div>
</div>

<script>
var dropzone = document.getElementById('dropzone');
var fileInput = document.getElementById('fileInput');
var submitBtn = document.getElementById('submitBtn');
var fileInfoArea = document.getElementById('fileInfoArea');

if(dropzone){
    ['dragenter','dragover'].forEach(function(e){
        dropzone.addEventListener(e,function(ev){ev.preventDefault();ev.stopPropagation();dropzone.classList.add('dragover')});
    });
    ['dragleave','drop'].forEach(function(e){
        dropzone.addEventListener(e,function(ev){ev.preventDefault();ev.stopPropagation();dropzone.classList.remove('dragover')});
    });
    dropzone.addEventListener('drop',function(ev){
        if(ev.dataTransfer.files.length){
            fileInput.files = ev.dataTransfer.files;
            showFile(ev.dataTransfer.files[0]);
        }
    });
    fileInput.addEventListener('change',function(){
        if(this.files.length) showFile(this.files[0]);
    });
}

function showFile(file){
    document.getElementById('fileName').textContent = file.name;
    document.getElementById('fileSize').textContent = (file.size/1024).toFixed(1)+' KB';
    fileInfoArea.style.display = 'block';
    dropzone.style.display = 'none';
    submitBtn.disabled = false;
}

function clearFile(){
    fileInput.value = '';
    fileInfoArea.style.display = 'none';
    dropzone.style.display = '';
    submitBtn.disabled = true;
}
</script>

<?php
echo '</div></div></div>';
?>
<div id="m_scroll_top" class="m-scroll-top"><i class="la la-arrow-up"></i></div>
<script src="includes/vendors/owl.carousel/dist/owl.carousel.js" type="text/javascript"></script>
</body>
</html>
