<?php
ob_start();
require("includes/check_auth_user.php");
require("includes/dbconnect.php");
require("includes/config.php");
require("includes/function.php");

$usertype = $_SESSION["usertype_" . $dbname];
$loguser  = $_SESSION["username_" . $dbname];

mysqli_select_db($conn, $dbname);

// ── Auto-migrate passmain for agentcode ──────────────────────────────────
$_chk = mysqli_query($conn, "SHOW COLUMNS FROM `passmain` LIKE 'agentcode'");
if ($_chk && mysqli_num_rows($_chk) == 0)
    mysqli_query($conn, "ALTER TABLE `passmain` ADD COLUMN `agentcode` INT(11) NOT NULL DEFAULT 0");

$formname = 'User Profile';

// Permission flags grouped to mirror the ACTUAL main menu structure of this
// app (Bag Trading Inventory) — replaces an older permission list that still
// referenced modules from a different project (Bill Confirming, Container,
// Port, Excess, Contra, Journal, Opening Balance, etc.) which don't exist here.
$permGroups = [
    'Masters' => [
        'customer'     => 'Customer',
        'supplier'     => 'Supplier',
        'agent'        => 'Salesman',
        'shipper'      => 'Shipper',
        'cha'          => 'CHA',
        'godown'       => 'Godown',
        'brand'        => 'Brand',
        'product'      => 'Product',
        'expense'      => 'Expense',
        'purchexpense' => 'Purchase Expense',
        'bank'         => 'Bank',
        'cash'         => 'Cash',
        'openbal'      => 'Opening Balance',
    ],
    'Order & Invoices' => [
        'saleorder'      => 'Sale Order',
        'dispatchalert'  => 'Dispatch Alert',
        'sale'           => 'Sale Invoice',
        'salegst'        => 'Sale GST Invoice',
        'salereturn'     => 'Sale Return',
    ],
    'Inventory' => [
        'purchentry'     => 'Purchase Entry',
        'purchreturn'    => 'Purchase Return',
        'purchaseexport' => 'Purchase Import',
        'inward'         => 'Inward',
        'outward'        => 'Outward',
        'damage'         => 'Damage',
        'transfer'       => 'Internal Transfer',
        'stockprod'      => 'Product Stock',
    ],
    'Accounts' => [
        'bankrecp'   => 'Bank Receipt',
        'bankpay'    => 'Bank Payment',
        'cashrecp'   => 'Cash Receipt',
        'cashpay'    => 'Cash Payment',
        'contra'     => 'Contra Entry',
        'jv'         => 'Journal Voucher',
        'discountgiven' => 'Discount Given',
        'discounttaken' => 'Discount Taken',
        'ledger'     => 'Ledger',
        'payablerep' => 'Payable',
        'receivable' => 'Receivable',
        'custaging'  => 'Customer Ageing Report',
    ],
    'Registers' => [
        'salereg'           => 'Sale Register',
        'salereturnreg'     => 'Sale Return Register',
        'salegstreg'        => 'Sale GST Register',
        'saleorderreg'      => 'Sale Order Register',
        'purreg'            => 'Purchase Register',
        'purchreturnreg'    => 'Purchase Return Register',
        'purchaseimportreg' => 'Purchase Import Register',
        'inwreg'            => 'Inward Register',
        'otwreg'            => 'Outward Register',
        'dmgreg'            => 'Damage Register',
        'transferreg'       => 'Transfer Register',
        'contrareg'         => 'Contra Register',
        'jvbook'            => 'JV Book',
        'salesmanperf'      => 'Salesman Performance Report',
        'custleading'       => 'Leading Customers Report',
    ],
];

// ── Auto-migrate passmain for any permission columns not created yet ─────
foreach ($permGroups as $_grp) {
    foreach ($_grp as $_fld => $_label) {
        $_chk = mysqli_query($conn, "SHOW COLUMNS FROM `passmain` LIKE '$_fld'");
        if ($_chk && mysqli_num_rows($_chk) == 0)
            mysqli_query($conn, "ALTER TABLE `passmain` ADD COLUMN `$_fld` VARCHAR(1) NOT NULL DEFAULT ''");
    }
}

$mode = isset($_GET['edit']) ? 'edit' : (isset($_GET['new']) ? 'new' : 'list');
if ($usertype != 1) {
    // Non-admins can only edit their own profile
    $mode = 'edit';
    $_GET['edit'] = $loguser;
}

// ── Delete ────────────────────────────────────────────────────────────────
if (isset($_GET['delete']) && $usertype == 1) {
    $code = (int)$_GET['delete'];
    mysqli_query($conn, "DELETE FROM `passmain` WHERE `code`='$code' AND `user`!='admin'") or die(mysqli_error($conn));
    delmess();
    header("refresh:1; url=profile.php");
}

// ── Save ──────────────────────────────────────────────────────────────────
if (isset($_POST['submit'])) {
    $code     = isset($_POST['code']) ? (int)$_POST['code'] : 0;
    $user     = mysqli_real_escape_string($conn, trim($_POST['user']));
    $password = mysqli_real_escape_string($conn, trim($_POST['password']));
    $newut    = ($usertype == 1 && isset($_POST['usertype'])) ? (int)$_POST['usertype'] : null;

    // ── Security: non-admins may only ever save their OWN account row.
    //    The `code` above comes straight from a hidden form field, which a
    //    non-admin could tamper with to overwrite another user's login, or
    //    (if set to 0) fall through to the "create new user" branch below
    //    and mint a brand-new account. Force it to their own row here so
    //    that's not possible no matter what the client sends. ────────────
    if ($usertype != 1) {
        $ownRow = mysqli_fetch_assoc(mysqli_query($conn,
            "SELECT `code` FROM `passmain` WHERE `user`='" . mysqli_real_escape_string($conn, $loguser) . "'"));
        $code = $ownRow ? (int)$ownRow['code'] : -1; // -1 = no valid own row → blocked below, never creates new
    }

    $a = 1;
    if ($user == '') { $a = 0; browse("Username Cannot Be Empty"); header("refresh:1; url=profile.php"); }

    if ($a == 1) {
        // Build permission fields
        $permSet = '';
        if ($usertype == 1) {
            foreach ($permGroups as $grp) {
                foreach ($grp as $fld => $label) {
                    $val = isset($_POST['perm_' . $fld]) ? 'Y' : '';
                    $permSet .= "`$fld`='$val', ";
                }
            }
        }

        if ($code > 0) {
            // Update existing
            $set = "`user`='$user'";
            if ($password != '') $set .= ", `password`='$password'";
            if ($newut !== null)  $set .= ", `usertype`='$newut'";
            if ($permSet != '')   $set .= ", " . rtrim($permSet, ', ');

            // If changing to Staff and no agent yet, auto-create agent in same DB year
            $existingRow = mysqli_fetch_assoc(mysqli_query($conn,"SELECT usertype,agentcode FROM `passmain` WHERE code='$code'"));
            if ($newut == 3 && (int)($existingRow['agentcode'] ?? 0) == 0) {
                $zdbYear = $_SESSION["zdbyear_".$dbname] ?? $dbname;
                mysqli_select_db($conn, $zdbYear);
                $maxAgent = mysqli_fetch_assoc(mysqli_query($conn,"SELECT MAX(accode) AS m FROM accmast"));
                $newAc = max(51, (int)($maxAgent['m'] ?? 50) + 1);
                $escUser = mysqli_real_escape_string($conn, $user);
                mysqli_query($conn,"INSERT INTO `accmast` (`accode`,`grpcode`,`name`,`adduser`,`adddate`,`addtime`) VALUES ('$newAc','040','$escUser','admin',CURDATE(),CURTIME())");
                mysqli_select_db($conn, $dbname);
                $set .= ", `agentcode`='$newAc'";
            }

            mysqli_query($conn, "UPDATE `passmain` SET $set WHERE `code`='$code'") or die(mysqli_error($conn));
            updmess();
            header("refresh:1; url=profile.php" . ($usertype == 1 ? "?edit=$code" : ""));
        } elseif ($usertype != 1) {
            // Non-admin with no valid own row to update — do NOT fall through
            // to account creation. Should not normally be reachable since
            // $code is forced above, but guarded here as a hard stop.
            browse("Not authorized to create users");
            header("refresh:1; url=profile.php");
        } else {
            // New user (admin only)
            if ($password == '') $password = '1234';
            $ut = $newut !== null ? $newut : 2;
            $newAgentCode = 0;
            // Auto-create agent in accmast for Staff users
            if ($ut == 3) {
                $zdbYear = $_SESSION["zdbyear_".$dbname] ?? $dbname;
                mysqli_select_db($conn, $zdbYear);
                $maxAgent = mysqli_fetch_assoc(mysqli_query($conn,"SELECT MAX(accode) AS m FROM accmast"));
                $newAgentCode = max(51, (int)($maxAgent['m'] ?? 50) + 1);
                $escUser = mysqli_real_escape_string($conn, $user);
                mysqli_query($conn,"INSERT INTO `accmast` (`accode`,`grpcode`,`name`,`adduser`,`adddate`,`addtime`) VALUES ('$newAgentCode','040','$escUser','admin',CURDATE(),CURTIME())");
                mysqli_select_db($conn, $dbname);
            }
            mysqli_query($conn, "INSERT INTO `passmain` (`user`,`password`,`usertype`,`agentcode`) VALUES ('$user','$password','$ut','$newAgentCode')") or die(mysqli_error($conn));
            $newcode = mysqli_insert_id($conn);

            if ($permSet != '') {
                mysqli_query($conn, "UPDATE `passmain` SET " . rtrim($permSet, ', ') . " WHERE `code`='$newcode'") or die(mysqli_error($conn));
            }
            insmess();
            header("refresh:1; url=profile.php?edit=$newcode");
        }
    }
}

// ── Fetch data ────────────────────────────────────────────────────────────
$users = [];
if ($mode == 'list') {
    $r = mysqli_query($conn, "SELECT * FROM `passmain` ORDER BY `code`") or die(mysqli_error($conn));
    while ($row = mysqli_fetch_assoc($r)) $users[] = $row;
}

$get = [];
if ($mode == 'edit' || $mode == 'new') {
    if ($mode == 'edit') {
        $editid = $_GET['edit'];
        if (is_numeric($editid)) {
            $r = mysqli_query($conn, "SELECT * FROM `passmain` WHERE `code`='" . (int)$editid . "'") or die(mysqli_error($conn));
        } else {
            $r = mysqli_query($conn, "SELECT * FROM `passmain` WHERE `user`='" . mysqli_real_escape_string($conn, $editid) . "'") or die(mysqli_error($conn));
        }
        $get = mysqli_fetch_assoc($r);
        if (!$get) $get = [];
    }
}

function fv($get, $key, $default = '') {
    return isset($get[$key]) ? htmlspecialchars($get[$key]) : $default;
}

include("includes/linkshead.php");
?>
<style>
    body { background:#f0f2f5; margin:0; padding:10px 14px; }

    .sim-card {
        background:#fff;
        border-radius:10px;
        box-shadow:0 1px 3px rgba(0,0,0,.08), 0 4px 16px rgba(0,0,0,.06);
        overflow:hidden;
    }
    .sim-card-header {
        background:#fff; border-bottom:2px solid #f1f5f9; padding:12px 20px;
        display:flex; align-items:center; justify-content:space-between;
    }
    .sim-card-header h2 { font-size:15px; font-weight:700; color:#1e293b; margin:0; }
    .sim-body { padding:20px; }

    table.ulist { width:100%; border-collapse:collapse; font-size:12.5px; }
    table.ulist th {
        background:#f8fafc; color:#374151; font-weight:700; font-size:11px;
        text-transform:uppercase; letter-spacing:.04em;
        padding:9px 12px; border-bottom:2px solid #e2e8f0; text-align:left;
    }
    table.ulist td { padding:8px 12px; border-bottom:1px solid #f1f5f9; }
    table.ulist tr:hover td { background:#f8fafc; }
    .badge-admin { background:#dbeafe; color:#1d4ed8; border-radius:20px; padding:2px 10px; font-size:11px; font-weight:600; }
    .badge-user  { background:#f1f5f9; color:#64748b; border-radius:20px; padding:2px 10px; font-size:11px; font-weight:600; }
    .badge-staff { background:#dcfce7; color:#166534; border-radius:20px; padding:2px 10px; font-size:11px; font-weight:600; }

    .act-link { color:#2563eb; text-decoration:none; font-size:12px; margin-right:10px; }
    .act-link.danger { color:#dc2626; }
    .act-link:hover { text-decoration:underline; }

    .fr { display:flex; align-items:center; margin-bottom:10px; gap:0; }
    .fr.fr-grid { display:grid; grid-template-columns: 1fr 1fr 1fr; gap:9px 14px; }
    .fl { display:flex; align-items:center; flex:1; }
    .lbl {
        font-size:12px; font-weight:500; color:#64748b; white-space:nowrap;
        text-align:right; padding-right:10px; min-width:110px; flex-shrink:0;
    }
    .finp {
        flex:1; padding:7px 11px; background:#f8fafc; border:1px solid #e2e8f0;
        border-radius:6px; font-size:12.5px; color:#1e293b; outline:none;
        width:100%; box-sizing:border-box; font-family:inherit;
    }
    .finp:focus { background:#fff; border-color:#3b82f6; box-shadow:0 0 0 3px rgba(59,130,246,.12); }

    .perm-section { margin-top:18px; border:1px solid #e2e8f0; border-radius:8px; overflow:hidden; }
    .perm-head {
        background:#f8fafc; padding:8px 14px; font-size:12px; font-weight:700;
        color:#374151; border-bottom:1px solid #e2e8f0;
    }
    .perm-body { padding:12px 14px; display:grid; grid-template-columns: repeat(auto-fill,minmax(160px,1fr)); gap:8px 14px; }
    .perm-item { display:flex; align-items:center; gap:7px; font-size:12.5px; color:#374151; }
    .perm-item input { width:15px; height:15px; cursor:pointer; }

    .btn {
        padding:8px 18px; border:none; border-radius:6px; font-size:12.5px; font-weight:600;
        cursor:pointer; display:inline-flex; align-items:center; gap:6px; text-decoration:none;
    }
    .btn-primary { background:#16a34a; color:#fff; }
    .btn-primary:hover { background:#15803d; }
    .btn-secondary { background:#64748b; color:#fff; }
    .btn-secondary:hover { background:#475569; }
    .btn-add { background:#2563eb; color:#fff; }
    .btn-add:hover { background:#1d4ed8; }

    .btn-bar { display:flex; justify-content:flex-end; gap:8px; padding:16px 20px; border-top:1px solid #f1f5f9; background:#fafafa; }
</style>

<body>

<div class="sim-card">
    <div class="sim-card-header">
        <h2><i class="fa fa-user" style="color:#3b82f6;margin-right:8px;font-size:14px;"></i><?php echo $formname; ?></h2>
        <?php if ($usertype == 1 && $mode == 'list'): ?>
        <a href="profile.php?new=1" class="btn btn-add"><i class="fa fa-plus"></i> Add User</a>
        <?php elseif ($usertype == 1 && $mode != 'list'): ?>
        <a href="profile.php" class="btn btn-secondary"><i class="fa fa-list"></i> All Users</a>
        <?php endif; ?>
    </div>

    <div class="sim-body">
    <?php if ($mode == 'list'): ?>

        <table class="ulist">
            <thead>
                <tr>
                    <th>Code</th>
                    <th>Username</th>
                    <th>Type</th>
                    <th style="text-align:right;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($users as $u): ?>
                <tr>
                    <td><?php echo $u['code']; ?></td>
                    <td><?php echo htmlspecialchars($u['user']); ?></td>
                    <td>
                        <?php if ($u['usertype'] == 1): ?>
                            <span class="badge-admin">Administrator</span>
                        <?php elseif ($u['usertype'] == 3): ?>
                            <span class="badge-staff">Staff (Salesman)</span>
                        <?php else: ?>
                            <span class="badge-user">Manager</span>
                        <?php endif; ?>
                    </td>
                    <td style="text-align:right;">
                        <a class="act-link" href="profile.php?edit=<?php echo $u['code']; ?>"><i class="fa fa-pencil"></i> Edit</a>
                        <?php if ($u['user'] != 'admin'): ?>
                        <a class="act-link danger" href="javascript:void(0)" onclick="confirmDelete('?delete=<?php echo $u['code']; ?>')"><i class="fa fa-trash"></i> Delete</a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

    <?php else: /* edit / new */ ?>

        <form action="" method="POST">
            <input type="hidden" name="code" value="<?php echo fv($get,'code','0'); ?>">

            <div class="fr fr-grid">
                <div class="fl">
                    <span class="lbl">Username <span style="color:#ef4444;">*</span></span>
                    <input type="text" name="user" class="finp" maxlength="20" required
                        value="<?php echo fv($get,'user'); ?>"
                        <?php echo (isset($get['user']) && $get['user'] == 'admin') ? 'readonly' : ''; ?>>
                </div>
                <div class="fl">
                    <span class="lbl">Password</span>
                    <input type="password" name="password" class="finp" maxlength="15" placeholder="<?php echo $mode=='new' ? 'Default: 1234' : 'Leave blank to keep current'; ?>">
                </div>
                <?php if ($usertype == 1): ?>
                <div class="fl">
                    <span class="lbl">User Type</span>
                    <select name="usertype" class="finp" <?php echo (isset($get['user']) && $get['user'] == 'admin') ? 'disabled' : ''; ?>>
                        <option value="2" <?php echo (fv($get,'usertype','2')==2) ? 'selected':''; ?>>Manager</option>
                        <option value="3" <?php echo (fv($get,'usertype')==3) ? 'selected':''; ?>>Staff (Salesman)</option>
                        <option value="1" <?php echo (fv($get,'usertype')==1) ? 'selected':''; ?>>Administrator</option>
                    </select>
                    <?php if (isset($get['user']) && $get['user'] == 'admin'): ?>
                    <input type="hidden" name="usertype" value="1">
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>

            <?php
            // Show linked agent for Staff users
            if (!empty($get['agentcode']) && (int)$get['agentcode'] > 0) {
                $zdbYear = $_SESSION["zdbyear_".$dbname] ?? $dbname;
                mysqli_select_db($conn, $zdbYear);
                $agRow = mysqli_fetch_assoc(mysqli_query($conn,"SELECT name FROM accmast WHERE accode='".(int)$get['agentcode']."'"));
                mysqli_select_db($conn, $dbname);
                $agName = $agRow ? htmlspecialchars($agRow['name']) : '—';
                echo '<div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:10px 14px;margin:10px 0;font-size:12.5px;color:#166534;">
                    <i class="fa fa-user-tie" style="margin-right:6px;"></i>
                    <b>Linked Agent:</b> ' . $agName . ' <span style="color:#94a3b8;">(Code #' . (int)$get['agentcode'] . ')</span>
                </div>';
            }
            ?>

            <?php if ($usertype == 1 && !(isset($get['user']) && $get['user'] == 'admin')): ?>
            <?php foreach ($permGroups as $grpname => $flds): ?>
            <div class="perm-section">
                <div class="perm-head"><?php echo htmlspecialchars($grpname); ?></div>
                <div class="perm-body">
                    <?php foreach ($flds as $fld => $label): ?>
                    <label class="perm-item">
                        <input type="checkbox" name="perm_<?php echo $fld; ?>" <?php echo (fv($get,$fld)=='Y') ? 'checked' : ''; ?>>
                        <?php echo htmlspecialchars($label); ?>
                    </label>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endforeach; ?>
            <?php elseif (isset($get['user']) && $get['user'] == 'admin'): ?>
            <div class="perm-section">
                <div class="perm-head">Permissions</div>
                <div class="perm-body">
                    <span style="color:#94a3b8;font-size:12.5px;">Administrator has full access to all modules.</span>
                </div>
            </div>
            <?php endif; ?>

            <div class="btn-bar">
                <?php if ($usertype == 1 && $mode != 'new'): ?>
                <a href="profile.php" class="btn btn-secondary"><i class="fa fa-times"></i> Cancel</a>
                <?php endif; ?>
                <button type="submit" name="submit" class="btn btn-primary"><i class="fa fa-check"></i> Save</button>
            </div>
        </form>

    <?php endif; ?>
    </div>
</div>

<?php include("includes/linksfoot.php"); ?>
</body>
</html>
