<?php
require_once __DIR__ . '/../app/bootstrap.php';

use App\Core\Auth;
use App\Core\Database;
use App\Core\PosService;
use App\Core\Security;

Auth::requireRole(['vendor', 'admin', 'staff'], 'public/login.php');
if (Auth::role() === 'staff') {
    Auth::requireAdminModule('pos-staff');
}
$panelType = 'vendor';
$pageTitle = 'POS Staff Roles | Vendor Panel';
$vendorId = (int)(PosService::currentVendorId() ?? 0);
if ($vendorId < 1) {
    http_response_code(403);
    exit('No approved vendor is assigned to this account.');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) {
        set_flash('error', 'Invalid security token.');
        redirect('vendor/pos-staff.php' . (Auth::role() !== 'vendor' ? '?vendor_id=' . $vendorId : ''));
    }
    try {
        $action = (string)($_POST['_action'] ?? 'assign');
        if ($action === 'deactivate') {
            $assignmentId = (int)($_POST['assignment_id'] ?? 0);
            Database::execute('UPDATE pos_staff_assignments SET status="inactive",updated_at=NOW() WHERE id=? AND vendor_id=?', [$assignmentId, $vendorId]);
            Security::logActivity(Auth::id(), 'pos_staff_deactivated', ['assignment_id' => $assignmentId, 'vendor_id' => $vendorId]);
            set_flash('success', 'POS staff assignment deactivated.');
        } else {
            $name = trim((string)($_POST['name'] ?? ''));
            $email = strtolower(trim((string)($_POST['email'] ?? '')));
            $password = (string)($_POST['password'] ?? '');
            $posRoleId = (int)($_POST['pos_role_id'] ?? 0);
            $registerId = max(0, (int)($_POST['register_id'] ?? 0));
            $outletId = max(0, (int)($_POST['outlet_id'] ?? 0));
            if ($name === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                throw new RuntimeException('Enter a valid name and email address.');
            }
            $roleRow = Database::fetchOne('SELECT code FROM pos_roles WHERE id=? LIMIT 1', [$posRoleId]);
            if (!$roleRow) throw new RuntimeException('Select a valid POS role.');
            $userRole = match ((string)$roleRow['code']) {
                'manager' => 'pos_manager',
                'viewer' => 'pos_reporter',
                default => 'pos_cashier',
            };
            if ($registerId > 0 && !Database::safeFetchOne('SELECT id FROM pos_registers WHERE id=? AND vendor_id=? AND status="active"', [$registerId, $vendorId])) {
                throw new RuntimeException('The selected register does not belong to this vendor.');
            }
            if ($outletId > 0 && !Database::safeFetchOne('SELECT id FROM pos_outlets WHERE id=? AND vendor_id=? AND status="active"', [$outletId, $vendorId])) {
                throw new RuntimeException('The selected outlet does not belong to this vendor.');
            }

            $user = Database::safeFetchOne('SELECT id,role,password_hash FROM users WHERE LOWER(email)=? AND status<>"deleted" LIMIT 1', [$email]);
            if (!$user) {
                if ($error = Security::passwordError($password, $email)) throw new RuntimeException($error);
                Database::execute(
                    'INSERT INTO users (role,name,email,password_hash,auth_version,status,created_at,updated_at) VALUES (?,?,?,?,1,"active",NOW(),NOW())',
                    [$userRole, $name, $email, password_hash($password, PASSWORD_DEFAULT)]
                );
                $userId = Database::lastInsertId();
            } else {
                $userId = (int)$user['id'];
                if (!in_array((string)$user['role'], ['pos_manager', 'pos_cashier', 'pos_reporter'], true)) {
                    throw new RuntimeException('That email belongs to an existing non-POS account and cannot be reassigned.');
                }
                $otherAssignment = Database::safeFetchOne('SELECT id FROM pos_staff_assignments WHERE user_id=? AND vendor_id<>? AND status="active" LIMIT 1', [$userId, $vendorId]);
                if ($otherAssignment) throw new RuntimeException('That POS account is already assigned to another vendor.');
                $params = [$userRole, $name];
                $sql = 'UPDATE users SET role=?,name=?,status="active"';
                if ($password !== '') {
                    if ($error = Security::passwordError($password, $email)) throw new RuntimeException($error);
                    $sql .= ',password_hash=?,auth_version=COALESCE(auth_version,1)+1,password_changed_at=NOW()';
                    $params[] = password_hash($password, PASSWORD_DEFAULT);
                }
                $sql .= ',updated_at=NOW() WHERE id=?';
                $params[] = $userId;
                Database::execute($sql, $params);
            }

            $assignment = Database::safeFetchOne('SELECT id FROM pos_staff_assignments WHERE vendor_id=? AND user_id=? ORDER BY id DESC LIMIT 1', [$vendorId, $userId]);
            if ($assignment) {
                Database::execute(
                    'UPDATE pos_staff_assignments SET pos_role_id=?,outlet_id=?,register_id=?,status="active",updated_at=NOW() WHERE id=? AND vendor_id=?',
                    [$posRoleId, $outletId ?: null, $registerId ?: null, $assignment['id'], $vendorId]
                );
            } else {
                Database::execute(
                    'INSERT INTO pos_staff_assignments (vendor_id,user_id,pos_role_id,outlet_id,register_id,status,created_at,updated_at) VALUES (?,?,?,?,?,"active",NOW(),NOW())',
                    [$vendorId, $userId, $posRoleId, $outletId ?: null, $registerId ?: null]
                );
            }
            Security::logActivity(Auth::id(), 'pos_staff_assigned', ['vendor_id' => $vendorId, 'user_id' => $userId, 'pos_role_id' => $posRoleId]);
            set_flash('success', 'POS staff assigned successfully.');
        }
    } catch (Throwable $exception) {
        set_flash('error', $exception->getMessage());
    }
    redirect('vendor/pos-staff.php' . (Auth::role() !== 'vendor' ? '?vendor_id=' . $vendorId : ''));
}

$roles = Database::safeFetchAll('SELECT * FROM pos_roles ORDER BY id ASC');
$registers = PosService::registers($vendorId);
$outlets = Database::safeFetchAll('SELECT * FROM pos_outlets WHERE vendor_id=? AND status="active" ORDER BY name', [$vendorId]);
$staff = Database::safeFetchAll(
    'SELECT psa.*,u.name,u.email,u.role,pr.name AS role_name,po.name outlet_name,preg.name register_name
     FROM pos_staff_assignments psa
     LEFT JOIN users u ON u.id=psa.user_id
     LEFT JOIN pos_roles pr ON pr.id=psa.pos_role_id
     LEFT JOIN pos_outlets po ON po.id=psa.outlet_id
     LEFT JOIN pos_registers preg ON preg.id=psa.register_id
     WHERE psa.vendor_id=? ORDER BY psa.id DESC',
    [$vendorId]
);
require_once ROOT_PATH . '/app/Layouts/panel_header.php';
?>
<div class="row g-3"><div class="col-lg-5"><div class="card module-card"><div class="card-header bg-white"><strong>Add POS Cashier / Manager</strong></div><div class="card-body"><form method="post"><?= csrf_field() ?><input type="hidden" name="_action" value="assign"><label class="form-label">Name</label><input class="form-control" name="name" required maxlength="150"><label class="form-label mt-2">Email</label><input class="form-control" name="email" type="email" required autocomplete="off"><label class="form-label mt-2">Temporary password</label><input class="form-control" name="password" type="password" minlength="<?= PASSWORD_MIN_LENGTH ?>" autocomplete="new-password"><div class="form-text">Required for a new POS account. Leave blank only when updating an existing POS account.</div><label class="form-label mt-2">POS Role</label><select class="form-select" name="pos_role_id" required><?php foreach($roles as $role): ?><option value="<?= (int)$role['id'] ?>"><?= e($role['name']) ?></option><?php endforeach; ?></select><label class="form-label mt-2">Outlet</label><select class="form-select" name="outlet_id"><option value="0">Any outlet</option><?php foreach($outlets as $outlet): ?><option value="<?= (int)$outlet['id'] ?>"><?= e($outlet['name']) ?></option><?php endforeach; ?></select><label class="form-label mt-2">Register</label><select class="form-select" name="register_id"><option value="0">All registers</option><?php foreach($registers as $register): ?><option value="<?= (int)$register['id'] ?>"><?= e($register['name']) ?></option><?php endforeach; ?></select><button class="btn btn-primary mt-3">Assign Staff</button></form></div></div></div><div class="col-lg-7"><div class="card module-card"><div class="card-header bg-white"><strong>Assigned POS Staff</strong></div><div class="table-responsive"><table class="table mb-0 align-middle"><thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Register</th><th>Status</th><th></th></tr></thead><tbody><?php if(!$staff): ?><?= table_empty(6,'No POS staff assigned.') ?><?php else: foreach($staff as $member): ?><tr><td><?= e($member['name']) ?></td><td><?= e($member['email']) ?></td><td><?= e($member['role_name'] ?? '') ?></td><td><?= e($member['register_name'] ?? 'All') ?></td><td><?= badge($member['status']) ?></td><td><?php if($member['status']==='active'): ?><form method="post" onsubmit="return confirm('Deactivate this POS assignment?')"><?= csrf_field() ?><input type="hidden" name="_action" value="deactivate"><input type="hidden" name="assignment_id" value="<?= (int)$member['id'] ?>"><button class="btn btn-sm btn-outline-danger">Deactivate</button></form><?php endif; ?></td></tr><?php endforeach; endif; ?></tbody></table></div></div></div></div>
<?php require_once ROOT_PATH . '/app/Layouts/panel_footer.php'; ?>
