« Back to History
company_departments.php
|
20260722_120325.php
Initial Domain Snapshot
Copy Code
<?php /* ============================================================================ File: /erp/company_departments.php Purpose: Simple (Login company only) — View + Add + Edit/Update + Delete Scope : Fix only inside this file. No global/base changes. ============================================================================ */ header('X-Frame-Options: SAMEORIGIN'); error_reporting(E_ALL); ini_set('display_errors','1'); require __DIR__ . '/modules/auth/page_acl.php'; $ctx = page_require_access('company_departments'); // ACL slug $u = $ctx['user']; $company_id = (int)$ctx['company_id']; $pdo = isset($ctx['pdo']) && $ctx['pdo'] instanceof PDO ? $ctx['pdo'] : null; require_once __DIR__ . '/helpers/activity_helper.php'; if(!$pdo){ require __DIR__ . '/core/db.php'; $pdo = $GLOBALS['pdo'] ?? $pdo; } if(!$pdo){ http_response_code(500); echo "DB not ready"; exit; } /* Helpers */ function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); } function pv($k,$d=null){ return isset($_POST[$k]) ? (is_array($_POST[$k])?$_POST[$k]:trim((string)$_POST[$k])) : $d; } function gv($k,$d=null){ return isset($_GET[$k]) ? trim((string)$_GET[$k]) : $d; } /* CSRF */ if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(16)); $CSRF = $_SESSION['csrf_token']; /* Flash */ $flash = ['ok'=>null,'msg'=>'']; /* Create / Update / Delete (only login company) */ if ($_SERVER['REQUEST_METHOD']==='POST' && pv('csrf_token')===$CSRF) { $action = pv('action',''); if ($action==='create') { $name = pv('name',''); $code = strtoupper(pv('code','')); $is_active = (int)!!pv('is_active',1); if ($name==='' || $code===''){ $flash=['ok'=>false,'msg'=>'Name & Code required']; } else { $du=$pdo->prepare("SELECT id FROM company_departments WHERE company_id=? AND code=? LIMIT 1"); $du->execute([$company_id,$code]); if ($du->fetchColumn()){ $flash=['ok'=>false,'msg'=>'Code already exists']; } else { $ins=$pdo->prepare("INSERT INTO company_departments (company_id,name,code,is_active,created_by,created_at) VALUES (?,?,?,?,?,NOW())"); $ok=$ins->execute([$company_id,$name,$code,$is_active,(int)$u['id']]); if($ok) { log_activity([ 'activity_type' => 'action', 'module_name' => 'company', 'action_name' => 'CREATE', 'reference_id' => (int)$pdo->lastInsertId(), 'activity_note' => "Created department: $name ($code)" ]); } $flash=['ok'=>$ok,'msg'=>$ok?'Added':'Insert failed']; if($ok){ header("Location: company_departments.php"); exit; } } } } if ($action==='update') { $id=(int)pv('id',0); $name = pv('name',''); $code = strtoupper(pv('code','')); $is_active = (int)!!pv('is_active',1); if ($id<=0 || $name==='' || $code===''){ $flash=['ok'=>false,'msg'=>'Invalid form']; } else { $chk=$pdo->prepare("SELECT id FROM company_departments WHERE id=? AND company_id=?"); $chk->execute([$id,$company_id]); if(!$chk->fetchColumn()){ $flash=['ok'=>false,'msg'=>'Row not in your company']; } else { $du=$pdo->prepare("SELECT id FROM company_departments WHERE company_id=? AND code=? AND id<>? LIMIT 1"); $du->execute([$company_id,$code,$id]); if ($du->fetchColumn()){ $flash=['ok'=>false,'msg'=>'Another row already uses this Code']; } else { $up=$pdo->prepare("UPDATE company_departments SET name=?, code=?, is_active=? WHERE id=? AND company_id=?"); $ok=$up->execute([$name,$code,$is_active,$id,$company_id]); log_activity([ 'activity_type' => 'action', 'module_name' => 'company', 'action_name' => 'UPDATE', 'reference_id' => $id, 'activity_note' => "Updated department ID: $id to $name" ]); $flash=['ok'=>$ok,'msg'=>$ok?'Updated':'Update failed']; if($ok){ header("Location: company_departments.php"); exit; } } } } } if ($action==='delete') { $id=(int)pv('id',0); if ($id<=0){ $flash=['ok'=>false,'msg'=>'Invalid delete request']; } else { // Safety: block if employees reference this department $inUse = 0; try { $c=$pdo->prepare("SELECT COUNT(*) FROM employees WHERE company_id=? AND department_id=?"); $c->execute([$company_id,$id]); $inUse=(int)$c->fetchColumn(); } catch (Throwable $e) { $inUse = 0; } if ($inUse>0) { $flash=['ok'=>false,'msg'=>"Can't delete: $inUse employee(s) linked to this department"]; } else { $del=$pdo->prepare("DELETE FROM company_departments WHERE id=? AND company_id=? LIMIT 1"); $ok=$del->execute([$id,$company_id]); log_activity([ 'activity_type' => 'action', 'module_name' => 'company', 'action_name' => 'DELETE', 'reference_id' => $id, 'activity_note' => "Deleted department ID: $id" ]); $flash=['ok'=>$ok,'msg'=>$ok?'Deleted':'Delete failed']; header("Location: company_departments.php"); exit; } } } } /* Edit row (if any) */ $edit_id = (int)gv('id',0); $edit_row = null; if ($edit_id>0){ $er=$pdo->prepare("SELECT id,name,code,is_active FROM company_departments WHERE id=? AND company_id=?"); $er->execute([$edit_id,$company_id]); $edit_row=$er->fetch(PDO::FETCH_ASSOC) ?: null; } /* List (View) */ $rows=[]; $st=$pdo->prepare("SELECT id,name,code,is_active,created_at FROM company_departments WHERE company_id=? ORDER BY created_at DESC, id DESC LIMIT 1000"); $st->execute([$company_id]); $rows=$st->fetchAll(PDO::FETCH_ASSOC); /* Company name for title */ $co=$pdo->prepare("SELECT name FROM companies WHERE id=?"); $co->execute([$company_id]); $company_name=$co->fetchColumn() ?: '(Company)'; ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width,initial-scale=1"/> <title>Departments — <?= h($company_name) ?></title> </head> <body class="page-dept"> <?php require_once __DIR__.'/partials/header.php'; ?> <div class="container-fluid py-4"> <div class="mb-4"> <h4 class="fw-bold">Departments — <?= h($company_name) ?></h4> </div> <?php if ($flash['ok']!==null): ?> <div class="alert <?= $flash['ok'] ? 'alert-success' : 'alert-danger' ?>"> <?= h($flash['msg']) ?> </div> <?php endif; ?> <!-- ===================== FORM SECTION ===================== --> <div class="card shadow-sm border-0 mb-4"> <div class="card-body"> <?php if ($edit_row): ?> <h5 class="fw-bold mb-3">Edit Department #<?= (int)$edit_row['id'] ?></h5> <?php else: ?> <h5 class="fw-bold mb-3">Add New Department</h5> <?php endif; ?> <form method="post" autocomplete="off"> <input type="hidden" name="csrf_token" value="<?= h($CSRF) ?>"> <input type="hidden" name="action" value="<?= $edit_row ? 'update' : 'create' ?>"> <?php if ($edit_row): ?> <input type="hidden" name="id" value="<?= (int)$edit_row['id'] ?>"> <?php endif; ?> <div class="row g-3"> <div class="col-md-4"> <label class="form-label">Name</label> <input type="text" name="name" value="<?= $edit_row ? h($edit_row['name']) : '' ?>" class="form-control" required> </div> <div class="col-md-3"> <label class="form-label">Code</label> <input type="text" name="code" value="<?= $edit_row ? h($edit_row['code']) : '' ?>" maxlength="10" class="form-control" required> </div> <div class="col-md-2 d-flex align-items-end"> <div class="form-check"> <input type="checkbox" name="is_active" value="1" class="form-check-input" <?= $edit_row ? ($edit_row['is_active']?'checked':'') : 'checked' ?>> <label class="form-check-label">Active</label> </div> </div> <div class="col-md-3 d-flex align-items-end gap-2"> <button class="btn btn-primary w-100" type="submit"> <?= $edit_row ? 'Update' : 'Submit' ?> </button> <?php if ($edit_row): ?> <a class="btn btn-outline-secondary w-100" href="company_departments.php"> Cancel </a> <?php else: ?> <button class="btn btn-outline-secondary w-100" type="reset"> Reset </button> <?php endif; ?> </div> </div> </form> <?php if ($edit_row): ?> <hr> <form method="post" onsubmit="return confirm('Delete this department permanently?');"> <input type="hidden" name="csrf_token" value="<?= h($CSRF) ?>"> <input type="hidden" name="action" value="delete"> <input type="hidden" name="id" value="<?= (int)$edit_row['id'] ?>"> <button class="btn btn-danger"> Delete Department </button> </form> <?php endif; ?> </div> </div> <!-- ===================== TABLE SECTION ===================== --> <div class="card shadow-sm border-0"> <div class="card-body"> <h6 class="fw-bold mb-3">Department List</h6> <div class="table-responsive"> <table class="table table-hover align-middle"> <thead class="table-light"> <tr> <th style="width:90px;">ID</th> <th>Name</th> <th>Code</th> <th style="width:120px;">Status</th> <th style="width:180px;">Created At</th> <th style="width:160px;">Action</th> </tr> </thead> <tbody> <?php if(!$rows): ?> <tr> <td colspan="6" class="text-center text-muted"> No departments found. </td> </tr> <?php else: foreach($rows as $r): ?> <tr> <td><?= (int)$r['id'] ?></td> <td><?= h($r['name']) ?></td> <td><?= h($r['code']) ?></td> <td> <?php if($r['is_active']): ?> <span class="badge bg-success-subtle text-success"> Active </span> <?php else: ?> <span class="badge bg-danger-subtle text-danger"> Inactive </span> <?php endif; ?> </td> <td><?= h($r['created_at']) ?></td> <td class="d-flex gap-2"> <a class="btn btn-sm btn-outline-secondary" href="company_departments.php?id=<?= (int)$r['id'] ?>"> Edit </a> <form method="post" onsubmit="return confirm('Delete this department permanently?');"> <input type="hidden" name="csrf_token" value="<?= h($CSRF) ?>"> <input type="hidden" name="action" value="delete"> <input type="hidden" name="id" value="<?= (int)$r['id'] ?>"> <button class="btn btn-sm btn-danger"> Delete </button> </form> </td> </tr> <?php endforeach; endif; ?> </tbody> </table> </div> </div> </div> </div> <?php require_once __DIR__.'/partials/footer.php'; ?>