« Back to History
karigar_register.php
|
20260721_154032.php
Initial Bulk Import
Copy Code
<?php /* ============================================================================= File: /erp/karigar_register.php Purpose: Register a Karigar into loom_karigar_master (company-scoped khata) Notes: - Khata dropdown comes from khatas table per current company - Selected khata_id is validated to belong to current company and its code is stored - Uses insert_dynamic() to only insert existing columns - Page-local changes only; follows ERP bootstrap/auth pattern ============================================================================= */ header('X-Frame-Options: SAMEORIGIN'); error_reporting(E_ALL); ini_set('display_errors',1); /* -------------------- 1) AUTH (Owner/Admin) --------------------------------- */ require __DIR__ . '/modules/auth/auth.php'; require_login(['Owner','Admin','Developer']); $u = auth_user(); // prefer session company (set by company-switch UI), fallback to auth_user company $company_id = (int)($_SESSION['company_id'] ?? $u['company_id'] ?? 0); $user_id = (int)($u['id'] ?? 0); /* -------------------- 2) PDO bootstrap (scoped) ------------------------------ */ $pdo = $GLOBALS['pdo'] ?? null; if (!$pdo) { require __DIR__ . '/core/db.php'; } /* -------------------- 3) Helpers -------------------------------------------- */ function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); } function pv($k,$d=null){ return isset($_POST[$k])?trim((string)$_POST[$k]):$d; } /* INFORMATION_SCHEMA helpers */ function table_columns(PDO $pdo, string $table): array { $q = $pdo->prepare("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?"); $q->execute([$table]); return array_map(static fn($r)=>$r['COLUMN_NAME'], $q->fetchAll(PDO::FETCH_ASSOC)); } function insert_dynamic(PDO $pdo, string $table, array $data): int { $colsAvail = array_flip(table_columns($pdo, $table)); $fields = []; $params = []; foreach ($data as $col=>$val) { if (isset($colsAvail[$col])) { $fields[] = $col; $params[] = $val; } } if (!$fields) throw new RuntimeException("No matching columns in $table"); $sql = "INSERT INTO $table (".implode(', ',$fields).") VALUES (".implode(',', array_fill(0,count($fields),'?')).")"; $st = $pdo->prepare($sql); $st->execute($params); return (int)$pdo->lastInsertId(); } /* -------------------- 4) Department & Role (soft) --------------------------- */ $DEPTS = []; $ROLES = []; try{ $st = $pdo->prepare("SELECT id,name FROM departments WHERE company_id = :cid ORDER BY name"); $st->execute([':cid'=>$company_id]); foreach($st->fetchAll(PDO::FETCH_ASSOC) as $r){ $DEPTS[(int)$r['id']] = (string)$r['name']; } }catch(Exception $e){} try{ $st = $pdo->prepare("SELECT id,name FROM roles WHERE company_id = :cid ORDER BY name"); $st->execute([':cid'=>$company_id]); foreach($st->fetchAll(PDO::FETCH_ASSOC) as $r){ $ROLES[(int)$r['id']] = (string)$r['name']; } }catch(Exception $e){} $DEPT_LOOM_ID = null; foreach($DEPTS as $id=>$nm){ if (mb_strtoupper($nm)==='LOOM'){ $DEPT_LOOM_ID=$id; break; } } $ROLE_KARIGAR_ID = null; foreach($ROLES as $id=>$nm){ if (mb_strtoupper($nm)==='KARIGAR'){ $ROLE_KARIGAR_ID=$id; break; } } if($DEPT_LOOM_ID===null) $DEPT_LOOM_ID = 19; if($ROLE_KARIGAR_ID===null) $ROLE_KARIGAR_ID = 12; /* -------------------- 5) Load khatas for current company --------------------- */ $KHATAS = []; try { $st = $pdo->prepare("SELECT id, code, name, machine_from, machine_to FROM khatas WHERE company_id = :cid ORDER BY id"); $st->execute([':cid' => $company_id]); $rows = $st->fetchAll(PDO::FETCH_ASSOC); if (is_array($rows)) { foreach ($rows as $r) { $KHATAS[(int)$r['id']] = [ 'code' => (string)($r['code'] ?? ''), 'name' => (string)($r['name'] ?? ''), 'from' => isset($r['machine_from']) ? (int)$r['machine_from'] : null, 'to' => isset($r['machine_to']) ? (int)$r['machine_to'] : null, ]; } } } catch (Exception $e) { $KHATAS = []; } /* -------------------- 6) Handle Submit -------------------------------------- */ $flash = ''; $new_id = null; /* sticky values */ $karigar_name = pv('karigar_name',''); $is_active = (int)pv('is_active',1); $dept_id = (int)pv('department_id',$DEPT_LOOM_ID); $role_id = (int)pv('role_id',$ROLE_KARIGAR_ID); // khata posted as id (not text) $posted_khata_id = isset($_POST['khata_id']) ? (int)$_POST['khata_id'] : 0; $machine_from = pv('machine_from',''); $machine_to = pv('machine_to',''); $entry_name = pv('entry_name',''); if($_SERVER['REQUEST_METHOD']==='POST'){ // Auto Entry Name if blank: "Name from-to" | "Name from" | "Name" if ($entry_name === '') { $tmp = $karigar_name; if ($machine_from !== '') { $tmp .= ' ' . $machine_from; if ($machine_to !== '') { $tmp .= '-' . $machine_to; } } $entry_name = trim($tmp); } // Server-side: validate posted khata belongs to this company $khata_id = null; $khata_code = null; if ($posted_khata_id > 0) { if (isset($KHATAS[$posted_khata_id])) { $khata_id = $posted_khata_id; $khata_code = $KHATAS[$posted_khata_id]['code'] ?? null; } else { // Defensive re-check against DB in case KHATAS was stale or tampered try { $chk = $pdo->prepare("SELECT code FROM khatas WHERE id = :id AND company_id = :cid LIMIT 1"); $chk->execute([':id' => $posted_khata_id, ':cid' => $company_id]); $r = $chk->fetch(PDO::FETCH_ASSOC); if ($r && isset($r['code'])) { $khata_id = $posted_khata_id; $khata_code = (string)$r['code']; } else { $khata_id = null; $khata_code = null; } } catch (Exception $e) { $khata_id = null; $khata_code = null; } } } // validation if ($karigar_name === '') { $flash = 'Karigar name is required.'; } elseif ($khata_id === null) { $flash = 'Please choose a valid Khata for this company.'; } else { try { /* CREATE TABLE if missing (safe on existing DB) */ $pdo->exec(" CREATE TABLE IF NOT EXISTS loom_karigar_master ( id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, company_id BIGINT UNSIGNED NOT NULL, khata_id BIGINT UNSIGNED NULL, khata_code VARCHAR(50) NULL, karigar_name VARCHAR(120) NOT NULL, machine_from INT NULL, machine_to INT NULL, entry_name VARCHAR(120) NULL, department_id BIGINT UNSIGNED NULL, role_id BIGINT UNSIGNED NULL, is_active TINYINT(1) NOT NULL DEFAULT 1, created_by BIGINT UNSIGNED NULL, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, INDEX idx_company_khata (company_id, khata_id), INDEX idx_company_role (company_id, department_id, role_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 "); /* Build data map; insert only columns that exist */ $data = [ 'company_id' => $company_id, 'khata_id' => $khata_id, 'khata_code' => $khata_code, 'karigar_name' => $karigar_name, 'machine_from' => ($machine_from !== '' ? (int)$machine_from : null), 'machine_to' => ($machine_to !== '' ? (int)$machine_to : null), 'entry_name' => ($entry_name !== '' ? $entry_name : null), 'department_id' => ($dept_id ?: null), 'role_id' => ($role_id ?: null), 'is_active' => ($is_active ? 1 : 0), 'created_by' => ($user_id ?: null), ]; $new_id = insert_dynamic($pdo, 'loom_karigar_master', $data); $flash = "Karigar saved (ID: {$new_id})."; /* Reset some fields post-insert */ $karigar_name = ''; $machine_from=''; $machine_to=''; $entry_name=''; $posted_khata_id = 0; } catch (Exception $e) { $flash = "Error: " . $e->getMessage(); } } } /* -------------------- 7) Use global header/footer (no inline CSS) ---------- */ require_once __DIR__ . '/partials/header.php'; ?> <div class="container-fluid py-4"> <div class="card shadow-sm border-0 mb-4"> <div class="card-body"> <div class="d-flex justify-content-between align-items-center mb-3"> <h4 class="fw-bold mb-0"> Loom Karigar Registration </h4> <span class="badge bg-secondary"> Company #<?= (int)$company_id ?> </span> </div> <?php if($flash): ?> <div class="alert alert-success"> <?= h($flash) ?> </div> <?php endif; ?> <form method="post" autocomplete="off"> <div class="row g-3"> <!-- Khata --> <div class="col-md-6"> <label class="form-label">Khata</label> <select name="khata_id" class="form-select" required> <option value="">-- Select Khata --</option> <?php if (!empty($KHATAS)): foreach($KHATAS as $kid => $k): ?> <option value="<?= (int)$kid ?>" <?= ($posted_khata_id===$kid)?'selected':''; ?>> <?= h($k['code'] . ' — ' . $k['name']); ?> </option> <?php endforeach; else: ?> <option value="">No khata defined for this company</option> <?php endif; ?> </select> <div class="form-text"> Choose khata for company (code — name). If not present, create khata under Masters. </div> </div> <!-- Status --> <div class="col-md-3"> <label class="form-label">Status</label> <select name="is_active" class="form-select"> <option value="1" <?= $is_active? 'selected':''; ?>>Active</option> <option value="0" <?= !$is_active? 'selected':''; ?>>Inactive</option> </select> </div> <!-- Karigar Name --> <div class="col-md-4"> <label class="form-label">Karigar Name</label> <input name="karigar_name" class="form-control" required value="<?= h($karigar_name) ?>"> </div> <!-- Department --> <div class="col-md-4"> <label class="form-label">Department</label> <select name="department_id" class="form-select"> <?php foreach($DEPTS as $id=>$nm): ?> <option value="<?= (int)$id ?>" <?= ($dept_id===$id)?'selected':''; ?>> <?= h($nm) ?> </option> <?php endforeach; ?> <?php if(empty($DEPTS)): ?> <option value="<?= (int)$DEPT_LOOM_ID ?>" <?= ($dept_id===$DEPT_LOOM_ID)?'selected':''; ?>> LOOM </option> <?php endif; ?> </select> </div> <!-- Role --> <div class="col-md-4"> <label class="form-label">Role</label> <select name="role_id" class="form-select"> <?php foreach($ROLES as $id=>$nm): ?> <option value="<?= (int)$id ?>" <?= ($role_id===$id)?'selected':''; ?>> <?= h($nm) ?> </option> <?php endforeach; ?> <?php if(empty($ROLES)): ?> <option value="<?= (int)$ROLE_KARIGAR_ID ?>" <?= ($role_id===$ROLE_KARIGAR_ID)?'selected':''; ?>> KARIGAR </option> <?php endif; ?> </select> </div> <!-- Machine From --> <div class="col-md-3"> <label class="form-label">Machine From</label> <input name="machine_from" type="number" inputmode="numeric" class="form-control" value="<?= h($machine_from) ?>"> </div> <!-- Machine To --> <div class="col-md-3"> <label class="form-label">Machine To</label> <input name="machine_to" type="number" inputmode="numeric" class="form-control" value="<?= h($machine_to) ?>"> </div> <!-- Entry Name --> <div class="col-md-6"> <label class="form-label">Entry Name (auto if blank)</label> <input name="entry_name" class="form-control" placeholder="auto: Name 5-8" value="<?= h($entry_name) ?>"> </div> <!-- Button --> <div class="col-12 text-end mt-3"> <button class="btn btn-primary px-4 fw-semibold" type="submit"> Save Karigar </button> </div> </div> </form> </div> </div> </div> <?php /* footer include (closes body/html and loads global scripts) */ require_once __DIR__ . '/partials/footer.php'; ?>