« Back to History
yarn_weight_data_manage.php
|
20260723_000646.php
Initial Domain Snapshot
Copy Code
<?php /* File: /erp/yarn_weight_data_manage.php Purpose: Manage (List / Add / Edit / Delete) yarn_weight_data Notes: - Company-level filtering enforced using $COMPANY_ID. - Dependent dropdowns: Stock Type (select) and Yarn Type -> Denier (dependent). - CSRF protection present. - Uses $pdo from $ctx; fallback to core/db.php only if $pdo not provided. */ /* ---- Auth + DB ---- */ require_once __DIR__ . '/modules/auth/page_acl.php'; $ctx = page_require_access('yarn_weight_data'); // change ACL key if needed require_once __DIR__ . '/modules/activity/activity_logger.php'; $u = $ctx['user'] ?? null; $COMPANY_ID = (int)($ctx['company_id'] ?? 0); $USER_ID = (int)($u['id'] ?? 0); $pdo = $ctx['pdo'] ?? null; if (!($pdo instanceof PDO)) { require __DIR__ . '/core/db.php'; } /* Start session only if not already started (safe) */ if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); } if (empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(24)); } $csrf = $_SESSION['csrf_token']; /* Helper: escape output */ function h($s) { return htmlspecialchars($s ?? '', ENT_QUOTES, 'UTF-8'); } $errors = []; $success = ''; /* POST handling: add / edit / delete */ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $token = $_POST['csrf_token'] ?? ''; if (!hash_equals($_SESSION['csrf_token'], $token)) { $errors[] = 'Invalid CSRF token.'; } else { $action = $_POST['action'] ?? ''; if ($action === 'add') { $stock_type = trim($_POST['stock_type'] ?? ''); $yarn_type = trim($_POST['yarn_type'] ?? ''); $denier = trim($_POST['denier'] ?? ''); $new_denier = trim($_POST['new_denier'] ?? ''); if ($stock_type === '' || $yarn_type === '') { $errors[] = 'Stock Type and Yarn Type are required.'; } if (empty($errors)) { $sql = "INSERT INTO yarn_weight_data (company_id, stock_type, yarn_type, denier, new_denier) VALUES (:cid, :stock_type, :yarn_type, :denier, :new_denier)"; try { $stmt = $pdo->prepare($sql); $stmt->execute([ ':cid' => $COMPANY_ID, ':stock_type' => $stock_type, ':yarn_type' => $yarn_type, ':denier' => $denier, ':new_denier' => $new_denier, ]); activity_log([ 'company_id' => $COMPANY_ID, 'user_id' => $USER_ID, 'module' => 'yarn', 'action_name' => 'create', 'entity_type' => 'yarn_weight_data', 'entity_id' => (int)$pdo->lastInsertId(), 'remarks' => 'Created yarn weight data' ]); $success = 'Record added successfully.'; } catch (PDOException $ex) { $errors[] = 'Database error: ' . $ex->getMessage(); } } } elseif ($action === 'edit') { $id = (int)($_POST['id'] ?? 0); $stock_type = trim($_POST['stock_type'] ?? ''); $yarn_type = trim($_POST['yarn_type'] ?? ''); $denier = trim($_POST['denier'] ?? ''); $new_denier = trim($_POST['new_denier'] ?? ''); if ($id <= 0) { $errors[] = 'Invalid record id.'; } if ($stock_type === '' || $yarn_type === '') { $errors[] = 'Stock Type and Yarn Type are required.'; } if (empty($errors)) { // Enforce company ownership in WHERE to prevent cross-company edits. $sql = "UPDATE yarn_weight_data SET stock_type = :stock_type, yarn_type = :yarn_type, denier = :denier, new_denier = :new_denier WHERE id = :id AND company_id = :cid"; try { $stmt = $pdo->prepare($sql); $stmt->execute([ ':stock_type' => $stock_type, ':yarn_type' => $yarn_type, ':denier' => $denier, ':new_denier' => $new_denier, ':id' => $id, ':cid' => $COMPANY_ID, ]); if ($stmt->rowCount() === 0) { $errors[] = 'No record updated. Verify the ID and company ownership.'; } else { activity_log([ 'company_id' => $COMPANY_ID, 'user_id' => $USER_ID, 'module' => 'yarn', 'action_name' => 'edit', 'entity_type' => 'yarn_weight_data', 'entity_id' => $id, 'remarks' => 'Updated yarn weight data' ]); $success = 'Record updated successfully.'; } } catch (PDOException $ex) { $errors[] = 'Database error: ' . $ex->getMessage(); } } } elseif ($action === 'delete') { $id = (int)($_POST['id'] ?? 0); if ($id <= 0) { $errors[] = 'Invalid record id.'; } if (empty($errors)) { // Enforce company ownership in WHERE. $sql = "DELETE FROM yarn_weight_data WHERE id = :id AND company_id = :cid"; try { $stmt = $pdo->prepare($sql); $stmt->execute([':id' => $id, ':cid' => $COMPANY_ID]); if ($stmt->rowCount() === 0) { $errors[] = 'No record deleted. Verify the ID and company ownership.'; } else { activity_log([ 'company_id' => $COMPANY_ID, 'user_id' => $USER_ID, 'module' => 'yarn', 'action_name' => 'delete', 'entity_type' => 'yarn_weight_data', 'entity_id' => $id, 'remarks' => 'Deleted yarn weight data' ]); $success = 'Record deleted successfully.'; } } catch (PDOException $ex) { $errors[] = 'Database error: ' . $ex->getMessage(); } } } else { $errors[] = 'Unknown action.'; } } } /* Fetch records for listing (company-scoped) */ try { $sqlList = "SELECT id, stock_type, yarn_type, denier, new_denier FROM yarn_weight_data WHERE company_id = :cid ORDER BY id ASC"; $stmt = $pdo->prepare($sqlList); $stmt->execute([':cid' => $COMPANY_ID]); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $ex) { $errors[] = 'Failed to fetch records: ' . $ex->getMessage(); $rows = []; } /* Load a record for editing if requested (company-scoped) */ $editing = false; $edit_row = null; if (isset($_GET['edit'])) { $eid = (int)$_GET['edit']; if ($eid > 0) { try { $sql = "SELECT id, stock_type, yarn_type, denier, new_denier FROM yarn_weight_data WHERE id = :id AND company_id = :cid"; $stmt = $pdo->prepare($sql); $stmt->execute([':id' => $eid, ':cid' => $COMPANY_ID]); $edit_row = $stmt->fetch(PDO::FETCH_ASSOC); if ($edit_row) $editing = true; else $errors[] = 'Record not found or not in your company.'; } catch (PDOException $ex) { $errors[] = 'Failed to load record for edit: ' . $ex->getMessage(); } } } /* ---------- Fetch stock types, yarn types & deniers mapping for this company ---------- */ $stock_types = []; $yarn_types = []; $yarn_map = []; // yarn_type => [denier1, denier2, ...] try { $sql = "SELECT DISTINCT IFNULL(stock_type,'') AS stock_type, IFNULL(yarn_types,'') AS yarn_types, IFNULL(denier,'') AS denier FROM yarn_company_data WHERE company_id = :cid ORDER BY stock_type ASC, yarn_types ASC, denier ASC"; $stmt = $pdo->prepare($sql); $stmt->execute([':cid' => $COMPANY_ID]); $rows_yc = $stmt->fetchAll(PDO::FETCH_ASSOC); foreach ($rows_yc as $r) { $st = trim($r['stock_type'] ?? ''); $yt = trim($r['yarn_types'] ?? ''); $dn = trim($r['denier'] ?? ''); if ($st !== '' && !in_array($st, $stock_types, true)) $stock_types[] = $st; if ($yt !== '' && !in_array($yt, $yarn_types, true)) $yarn_types[] = $yt; if ($yt === '') continue; if ($dn === '') continue; if (!isset($yarn_map[$yt])) $yarn_map[$yt] = []; if (!in_array($dn, $yarn_map[$yt], true)) $yarn_map[$yt][] = $dn; } } catch (PDOException $ex) { // non-fatal: leave arrays empty and page will still work $stock_types = []; $yarn_types = []; $yarn_map = []; } /* Output: header, content, footer */ require_once __DIR__ . '/partials/header.php'; ?> <div class="card"> <div class="card-header"> <h3>Yarn Weight Data — Manage</h3> </div> <div class="card-body"> <?php if (!empty($errors)): ?> <div class="notice notice-danger"> <?php foreach ($errors as $e): ?> <div><?php echo h($e); ?></div> <?php endforeach; ?> </div> <?php endif; ?> <?php if ($success): ?> <div class="notice notice-success"><?php echo h($success); ?></div> <?php endif; ?> <div class="card"> <div class="card-body"> <h4><?php echo $editing ? 'Edit Record' : 'Add New Record'; ?></h4> <form method="post" class="form-grid"> <input type="hidden" name="csrf_token" value="<?php echo h($csrf); ?>"> <input type="hidden" name="action" value="<?php echo $editing ? 'edit' : 'add'; ?>"> <?php if ($editing): ?> <input type="hidden" name="id" value="<?php echo (int)$edit_row['id']; ?>"> <?php endif; ?> <!-- Stock Type (select) --> <div class="form-group"> <label>Stock Type</label> <select name="stock_type" id="stock_type_sel" class="form-control" required> <option value="">-- Select Stock Type --</option> <?php foreach ($stock_types as $st): ?> <option value="<?php echo h($st); ?>" <?php echo ($editing && ($edit_row['stock_type'] === $st)) ? 'selected' : ''; ?>><?php echo h($st); ?></option> <?php endforeach; ?> </select> </div> <!-- Yarn Type (select) --> <div class="form-group"> <label>Yarn Type</label> <select name="yarn_type" id="yarn_type_sel" class="form-control" required> <option value="">-- Select Yarn Type --</option> <?php foreach ($yarn_types as $yt): ?> <option value="<?php echo h($yt); ?>" <?php echo ($editing && ($edit_row['yarn_type'] === $yt)) ? 'selected' : ''; ?>><?php echo h($yt); ?></option> <?php endforeach; ?> </select> </div> <!-- Denier (dependent select) --> <div class="form-group"> <label>Denier</label> <select name="denier" id="denier_sel" class="form-control"> <option value="">-- Select Denier --</option> <?php // If editing, prefill denier options for the selected yarn_type if ($editing && !empty($edit_row['yarn_type'])) { $pref_yt = $edit_row['yarn_type']; $pref_deniers = $yarn_map[$pref_yt] ?? []; foreach ($pref_deniers as $d) { $sel = ($editing && ($edit_row['denier'] === $d)) ? 'selected' : ''; echo '<option value="'.h($d).'" '.$sel.'>'.h($d).'</option>'; } } ?> </select> </div> <div class="form-group"> <label>New Denier</label> <input name="new_denier" class="form-control" value="<?php echo h($editing ? $edit_row['new_denier'] : ''); ?>"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary"><?php echo $editing ? 'Update' : 'Add'; ?></button> <?php if ($editing): ?> <a class="btn btn-secondary" href="yarn_weight_data_manage.php">Cancel</a> <?php endif; ?> </div> </form> </div> </div> <div class="card" style="margin-top:1rem"> <div class="card-body"> <h4>Existing Records</h4> <table class="table table-striped"> <thead> <tr> <th>#</th> <th>Stock Type</th> <th>Yarn Type</th> <th>Denier</th> <th>New Denier</th> <th>Actions</th> </tr> </thead> <tbody> <?php if (empty($rows)): ?> <tr><td colspan="6">No records found.</td></tr> <?php else: ?> <?php foreach ($rows as $r): ?> <tr> <td><?php echo (int)$r['id']; ?></td> <td><?php echo h($r['stock_type']); ?></td> <td><?php echo h($r['yarn_type']); ?></td> <td><?php echo h($r['denier']); ?></td> <td><?php echo h($r['new_denier']); ?></td> <td> <a class="btn btn-sm" href="?edit=<?php echo (int)$r['id']; ?>">Edit</a> <form method="post" style="display:inline" onsubmit="return confirm('Delete this record?');"> <input type="hidden" name="csrf_token" value="<?php echo h($csrf); ?>"> <input type="hidden" name="action" value="delete"> <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>"> <button type="submit" class="btn btn-sm btn-danger">Delete</button> </form> </td> </tr> <?php endforeach; ?> <?php endif; ?> </tbody> </table> </div> </div> </div> </div> <!-- Client-side script to populate dependent denier dropdown --> <script> (function(){ var yarnMap = <?php echo json_encode($yarn_map, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP); ?>; var yarnSel = document.getElementById('yarn_type_sel'); var denierSel = document.getElementById('denier_sel'); function clearDenier() { denierSel.innerHTML = ''; var o = document.createElement('option'); o.value = ''; o.textContent = '-- Select Denier --'; denierSel.appendChild(o); } function populateDenierFor(yt) { clearDenier(); if (!yt) return; var deniers = yarnMap[yt] || []; deniers.forEach(function(d){ var opt = document.createElement('option'); opt.value = d; opt.textContent = d; denierSel.appendChild(opt); }); } if (yarnSel) { yarnSel.addEventListener('change', function(){ populateDenierFor(this.value); }); } // On DOM ready ensure denier list is populated if yarn selected document.addEventListener('DOMContentLoaded', function(){ if (yarnSel && yarnSel.value) { populateDenierFor(yarnSel.value); <?php if ($editing && !empty($edit_row['denier'])): ?> var want = <?php echo json_encode($edit_row['denier']); ?>; for (var i=0;i<denierSel.options.length;i++){ if (denierSel.options[i].value === want) { denierSel.selectedIndex = i; break; } } <?php endif; ?> } }); })(); </script> <?php require_once __DIR__ . '/partials/footer.php';