<?php
require_once __DIR__ . '/../../includes/init.php';
middleware(['super_admin']);

$db     = getDBConnection();
$id     = (int)($_GET['id'] ?? 0);
$isEdit = ($id > 0);
$user   = [];

if ($isEdit) {
    $user = dbRow($db, "SELECT * FROM users WHERE id=?", [$id]);
    if (!$user) redirect(BASE_URL . '/modules/admin/users.php');
}

// ── Division → Sub-division map ───────────────────────────────
$DIVISIONS = [
    'Roorkee Urban'  => ['ROORKEE_SD-I', 'ROORKEE_SD-II', 'EDSD DHANORI'],
    'Ramnagar'       => ['EDSD-I RAMNAGAR ROORKEE', 'EDSD-II RAMNAGAR ROORKEE', 'EDSD HIMALAYAN'],
    'Roorkee Rural'  => ['MANGLORE', 'EDSD JHEBREDA', 'LANDHAURA'],
];

$error   = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validateCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid request.';
    } else {
        $fullName = trim($_POST['full_name'] ?? '');
        $username = trim($_POST['username'] ?? '');
        $role     = $_POST['role'] ?? '';
        $phone    = trim($_POST['phone'] ?? '');
        $password = $_POST['password'] ?? '';
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        // Division: super_admin gets 'All', everyone else selects sub-divisions
        if ($role === 'super_admin') {
            $divisionVal = 'All';
        } else {
            $selectedSubs = $_POST['sub_divisions'] ?? [];
            $divisionVal  = !empty($selectedSubs) ? json_encode(array_values($selectedSubs)) : null;
        }

        $validRoles = ['super_admin','exn','sdo','je','mr'];

        if (!$fullName || !$username || !$role) {
            $error = 'Full name, username, and role are required.';
        } elseif (!in_array($role, $validRoles)) {
            $error = 'Invalid role.';
        } elseif (!$isEdit && strlen($password) < 6) {
            $error = 'Password must be at least 6 characters.';
        } elseif ($isEdit && $password && strlen($password) < 6) {
            $error = 'New password must be at least 6 characters.';
        } else {
            try {
                if ($isEdit) {
                    if ($password) {
                        $db->prepare("UPDATE users SET full_name=?,username=?,role=?,division=?,phone=?,is_active=?,password=?,updated_at=NOW() WHERE id=?")
                           ->execute([$fullName,$username,$role,$divisionVal,$phone?:null,$isActive,password_hash($password,PASSWORD_BCRYPT),$id]);
                    } else {
                        $db->prepare("UPDATE users SET full_name=?,username=?,role=?,division=?,phone=?,is_active=?,updated_at=NOW() WHERE id=?")
                           ->execute([$fullName,$username,$role,$divisionVal,$phone?:null,$isActive,$id]);
                    }
                    $success = 'User updated successfully.';
                    $user = dbRow($db, "SELECT * FROM users WHERE id=?", [$id]);
                } else {
                    $db->prepare("INSERT INTO users (full_name,username,password,role,division,phone,is_active) VALUES (?,?,?,?,?,?,?)")
                       ->execute([$fullName,$username,password_hash($password,PASSWORD_BCRYPT),$role,$divisionVal,$phone?:null,$isActive]);
                    redirect(BASE_URL . '/modules/admin/users.php');
                }
            } catch (PDOException $e) {
                $error = (strpos($e->getMessage(),'Duplicate') !== false) ? 'Username already exists.' : 'Database error.';
            }
        }
    }
}

// Parse saved sub-divisions for all non-super_admin roles
$savedSubs = [];
if ($isEdit && !empty($user['division']) && $user['division'] !== 'All') {
    $decoded   = json_decode($user['division'], true);
    $savedSubs = is_array($decoded) ? $decoded : [$user['division']];
}

// Consumer count per sub-division
$consumerCounts = [];
try {
    $rows = dbRows($db, "SELECT division, COUNT(*) AS cnt FROM consumers WHERE is_active=1 GROUP BY division");
    foreach ($rows as $r) { $consumerCounts[$r['division']] = (int)$r['cnt']; }
} catch (PDOException $e) {}

$pageTitle = $isEdit ? 'Edit User' : 'Add User';
include __DIR__ . '/../../includes/header.php';
?>

<?php if ($error):   ?><div class="alert alert-danger"><?= h($error) ?></div><?php endif; ?>
<?php if ($success): ?><div class="alert alert-success"><?= h($success) ?></div><?php endif; ?>

<div class="erp-card" style="max-width:580px;">
    <form method="POST" novalidate id="userForm">
        <input type="hidden" name="csrf_token" value="<?= generateCsrfToken() ?>">

        <div class="mb-3">
            <label class="form-label fw-semibold">Full Name <span class="text-danger">*</span></label>
            <input type="text" name="full_name" class="form-control" required
                   value="<?= h($user['full_name'] ?? '') ?>" placeholder="Enter full name">
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold">Username <span class="text-danger">*</span></label>
            <input type="text" name="username" class="form-control" required
                   value="<?= h($user['username'] ?? '') ?>" placeholder="Unique login username">
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold">Role <span class="text-danger">*</span></label>
            <select name="role" class="form-select" required id="roleSelect" onchange="toggleDivision()">
                <option value="">-- Select Role --</option>
                <?php foreach (['super_admin'=>'Super Admin','exn'=>'EXN','sdo'=>'SDO','je'=>'JE','mr'=>'Meter Reader'] as $v=>$l): ?>
                <option value="<?= $v ?>" <?= ($user['role']??'')===$v?'selected':'' ?>><?= $l ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold">
                Password <?= $isEdit ? '<small class="fw-normal text-muted">(leave blank to keep)</small>' : '<span class="text-danger">*</span>' ?>
            </label>
            <div class="input-group">
                <input type="password" name="password" id="passInput" class="form-control"
                       placeholder="<?= $isEdit?'New password (optional)':'Min 6 characters' ?>"
                       <?= !$isEdit?'required':'' ?> autocomplete="new-password">
                <button type="button" class="input-group-text bg-white" onclick="togglePass()">
                    <i class="bi bi-eye" id="passIcon"></i>
                </button>
            </div>
        </div>

        <!-- Sub-division: shown for all roles except super_admin -->
        <div class="mb-3" id="divisionSection" style="display:none;">
            <label class="form-label fw-semibold">
                Sub-division Assignment
                <small class="fw-normal text-muted">(User will only see data from selected sub-divisions)</small>
            </label>

            <?php foreach ($DIVISIONS as $divName => $subs):
                // Total consumers in this parent division
                $parentCount = 0;
                foreach ($subs as $s) { $parentCount += $consumerCounts[$s] ?? 0; }
            ?>
            <div class="mb-2" style="border:1px solid var(--erp-border);border-radius:8px;overflow:hidden;">

                <!-- Parent division label -->
                <div class="px-3 py-2 fw-semibold d-flex align-items-center justify-content-between"
                     style="background:var(--erp-primary-light);font-size:.85rem;">
                    <span>
                        <i class="bi bi-diagram-3 me-2" style="color:var(--erp-primary);"></i>
                        <?= h($divName) ?>
                        <span class="badge ms-2" style="background:#1a237e;font-size:.7rem;font-weight:600;">
                            <?= $parentCount ?> consumers
                        </span>
                    </span>
                    <button type="button" class="btn btn-sm btn-link p-0 text-primary"
                            style="font-size:.75rem;text-decoration:none;"
                            onclick="toggleAll('<?= h($divName) ?>', this)">Select All</button>
                </div>

                <!-- Sub-divisions -->
                <div class="px-3 py-2" style="background:var(--erp-surface);">
                    <?php foreach ($subs as $sub):
                        $subCount = $consumerCounts[$sub] ?? 0;
                    ?>
                    <label class="d-flex align-items-center gap-2 py-1" style="cursor:pointer;font-size:.85rem;">
                        <input type="checkbox"
                               class="form-check-input mt-0 sub-cb-<?= preg_replace('/[^a-z0-9]/i','_', $divName) ?>"
                               name="sub_divisions[]"
                               value="<?= h($sub) ?>"
                               <?= in_array($sub, $savedSubs)?'checked':'' ?>>
                        <i class="bi bi-arrow-return-right text-muted" style="font-size:.72rem;"></i>
                        <?= h($sub) ?>
                        <span class="badge bg-secondary ms-auto" style="font-size:.7rem;"><?= $subCount ?></span>
                    </label>
                    <?php endforeach; ?>
                </div>

            </div>
            <?php endforeach; ?>

            <div class="text-muted mt-1" style="font-size:.76rem;">
                <i class="bi bi-info-circle me-1"></i>
                If no sub-division selected, user can see all data.
            </div>
        </div>

        <div class="mb-3">
            <label class="form-label fw-semibold">Phone</label>
            <input type="tel" name="phone" class="form-control"
                   value="<?= h($user['phone'] ?? '') ?>" placeholder="Mobile number">
        </div>

        <div class="mb-4">
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" name="is_active" id="isActive"
                       <?= ($user['is_active'] ?? 1) ? 'checked' : '' ?>>
                <label class="form-check-label fw-semibold" for="isActive">Account Active</label>
            </div>
        </div>

        <div class="d-flex gap-2">
            <button type="submit" class="btn btn-erp flex-fill">
                <i class="bi bi-<?= $isEdit?'check-lg':'person-plus-fill' ?> me-2"></i>
                <?= $isEdit ? 'Update User' : 'Create User' ?>
            </button>
            <a href="<?= BASE_URL ?>/modules/admin/users.php" class="btn btn-outline-secondary">Cancel</a>
        </div>
    </form>
</div>

<script>
function togglePass() {
    const i = document.getElementById('passInput'), c = document.getElementById('passIcon');
    i.type = i.type === 'password' ? 'text' : 'password';
    c.className = i.type === 'password' ? 'bi bi-eye' : 'bi bi-eye-slash';
}

function toggleDivision() {
    const role = document.getElementById('roleSelect').value;
    document.getElementById('divisionSection').style.display = (role && role !== 'super_admin') ? '' : 'none';
}

function toggleAll(divName, btn) {
    const cls   = 'sub-cb-' + divName.replace(/[^a-z0-9]/gi, '_');
    const boxes = document.querySelectorAll('.' + cls);
    const allChecked = [...boxes].every(b => b.checked);
    boxes.forEach(b => b.checked = !allChecked);
    btn.textContent = allChecked ? 'Select All' : 'Deselect All';
}

// Init on page load
toggleDivision();
</script>

<?php include __DIR__ . '/../../includes/footer.php'; ?>
